本文整理汇总了Python中sortedcontainers.SortedSet.remove方法的典型用法代码示例。如果您正苦于以下问题:Python SortedSet.remove方法的具体用法?Python SortedSet.remove怎么用?Python SortedSet.remove使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sortedcontainers.SortedSet
的用法示例。
在下文中一共展示了SortedSet.remove方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: DictGraph
# 需要导入模块: from sortedcontainers import SortedSet [as 别名]
# 或者: from sortedcontainers.SortedSet import remove [as 别名]
class DictGraph(Graph):
"""Graph that supports nonconsecutive vertex ids."""
def __init__(self, nodes: Set[int]=None, r: int=1) -> None:
"""Make a new graph."""
if nodes is None:
self.nodes = SortedSet() # type: Set[int]
else:
self.nodes = nodes
self.radius = r
self.inarcs_by_weight = [defaultdict(SortedSet) for _ in range(self.radius)]
def __len__(self):
"""len() support."""
return len(self.nodes)
def __iter__(self):
"""Iteration support."""
return iter(self.nodes)
def __contains__(self, v):
"""Support for `if v in graph`."""
return v in self.nodes
def add_node(self, u: int):
"""Add a new node."""
self.nodes.add(u)
def arcs(self, weight: int=None):
"""
Return all the arcs in the graph.
restrict to a given weight when provided
"""
if weight:
return [(x, y) for x in self.nodes
for y in self.inarcs_by_weight[weight-1][x]]
else:
return [(x, y, w+1) for w, arc_list in
enumerate(self.inarcs_by_weight)
for x in self.nodes
for y in arc_list[x]]
def remove_isolates(self) -> List[int]:
"""
Remove all isolated vertices and return a list of vertices removed.
Precondition: the graph is bidirectional
"""
isolates = [v for v in self if self.in_degree(v, 1) == 0]
for v in isolates:
self.nodes.remove(v)
for N in self.inarcs_by_weight:
if v in N:
del N[v]
return isolates
示例2: __init__
# 需要导入模块: from sortedcontainers import SortedSet [as 别名]
# 或者: from sortedcontainers.SortedSet import remove [as 别名]
class FileReference:
"""A class that manages n-triple files.
This class stores inforamtation about the location of a n-triple file and is
able to add and delete triples to that file.
"""
def __init__(self, path, content):
"""Initialize a new FileReference instance.
Args:
filelocation: A string of the filepath.
filecontentinmem: Boolean to decide if local filesystem should be used to
or if file content should be kept in memory too . (Defaults false)
Raises:
ValueError: If no file at the filelocation, or in the given directory + filelocation.
"""
if isinstance(content, str):
new = []
for line in content.splitlines():
new.append(' '.join(line.split()))
content = new
self._path = path
self._content = SortedSet(content)
self._modified = False
@property
def path(self):
return self._path
@property
def content(self):
return "\n".join(self._content) + "\n"
def add(self, data):
"""Add a triple to the file content."""
self._content.add(data)
def extend(self, data):
"""Add triples to the file content."""
self._content.extend(data)
def remove(self, data):
"""Remove trple from the file content."""
try:
self._content.remove(data)
except KeyError:
pass
示例3: revealed2sortedset
# 需要导入模块: from sortedcontainers import SortedSet [as 别名]
# 或者: from sortedcontainers.SortedSet import remove [as 别名]
def revealed2sortedset(revealed: List[Union[tuple, slice]]) -> SortedSet:
""" Converts a list of included pairs to a sorted set of integers in O(n), n = size of @slices.
Every number from every slice is added to the sorted set, except 0.
"""
# 10, [] -> 10, []
# 10, [(0, 10)] -> 10, [10]
# 10, [(0, 7)] -> 10, [7]
# 10, [(7, 10)] -> 10, [7, 10]
# 10, [(3, 7)] -> 10, [3, 7]
# 10, [(0, 3), (7, 10)] -> 10, [3, 7, 10]
# 10, [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)] -> 10, [1, 2, 3, 4, 5, 6, 7, 8, 9]
try:
#intervals = SortedSet(a for a, _ in revealed).union(b for _, b in revealed)
intervals = SortedSet()
for a, b in revealed:
intervals.add(a)
intervals.add(b)
except TypeError: # slice
intervals = SortedSet(sl.start for sl in revealed).union(sl.stop for sl in revealed)
if 0 in intervals:
intervals.remove(0)
return intervals
示例4: eliminationOrder
# 需要导入模块: from sortedcontainers import SortedSet [as 别名]
# 或者: from sortedcontainers.SortedSet import remove [as 别名]
def eliminationOrder(gm, orderMethod=None, nExtra=-1, cutoff=inf, priority=None, target=None):
"""Find an elimination order for a graphical model
Args:
gm (GraphModel): A graphical model object
method (str): Heuristic method; one of {'minfill','wtminfill','minwidth','wtminwidth','random'}
nExtra (int): Randomly select eliminated variable from among the best plus nExtra; this adds
randomness to the order selection process. 0 => randomly from best; -1 => no randomness (default)
cutoff (float): Quit early if ``score`` exceeds a user-supplied cutoff value (returning ``target, cutoff``)
priority (list, optional): Optional list of variable priorities; lowest priority variables are
eliminated first. Useful for mixed elimination models, such as marginal MAP inference tasks.
target (list): If the identified order is better than cutoff, write it directly into passed ``target`` list
Returns:
list: The identified elimination order
float: The "score" of this ordering
Using ``target`` and ``cutoff`` one can easily search for better orderings by repeated calls:
>>> ord, score = eliminationOrder(model, 'minfill', nExtra=2, cutoff=score, target=ord)
"""
orderMethod = 'minfill' if orderMethod is None else orderMethod.lower()
priority = [1 for x in gm.X] if priority is None else priority
if orderMethod == 'minfill': score = lambda adj,Xj: 0.5*sum([len(adj[Xj]-adj[Xk]) for Xk in adj[Xj]])
elif orderMethod == 'wtminfill': score = lambda adj,Xj: sum([(adj[Xj]-adj[Xk]).nrStatesDouble() for Xk in adj[Xj]])
elif orderMethod == 'minwidth': score = lambda adj,Xj: len(adj[Xj])
elif orderMethod == 'wtminwidth': score = lambda adj,Xj: adj[Xj].nrStatesDouble()
elif orderMethod == 'random': score = lambda adj,Xj: np.random.rand()
else: raise ValueError('Unknown ordering method: {}'.format(orderMethod))
adj = [ gm.markovBlanket(Xi) for Xi in gm.X ] # build MRF
# initialize priority queue of scores using e.g. heapq or sort
reverse = [ (priority[Xi],score(adj,Xi),Xi) for Xi in gm.X ]
scores = SortedSet( reverse );
totalSize = 0.0
#_order = np.zeros((len(gm.X),)) #np.array([0 for Xi in gm.X])
_order = [0]*len(gm.X)
for idx in range(gm.nvar):
pick = 0
Pi,Si,Xi = scores[pick]
if nExtra >= 0:
mx = bisect.bisect_right(scores, (Pi,Si,gm.X[-1])) # get one past last equal-priority & score vars
pick = min(mx+nExtra, len(scores)) # then pick a random "near-best" variable
pick = np.random.randint(pick)
Pi,Si,Xi = scores[pick]
del scores[pick]
_order[idx] = Xi.label # write into order[idx] = Xi
totalSize += adj[Xi].nrStatesDouble()
if totalSize > cutoff: return target,cutoff # if worse than cutoff, quit with no changes to "target"
fix = VarSet()
for Xj in adj[Xi]:
adj[Xj] |= adj[Xi]
adj[Xj] -= [Xi] # TODO adj[Xj].remove(Xi) slightly faster but still unsupported by cython version
fix |= adj[Xj] # shouldn't need to fix as much for min-width?
for Xj in fix:
Pj,Sj,Xj = reverse[Xj]
scores.remove(reverse[Xj])
reverse[Xj] = (Pj,score(adj,Xj),Xj)
scores.add(reverse[Xj]) # add (Pj,score(adj,Xj),Xj) to heap & update reverse lookup
if not (target is None):
target.extend([None for i in range(len(target),len(_order))]) # make sure order is the right size
for idx in range(gm.nvar): target[idx]=_order[idx] # copy result if completed without quitting
return _order,totalSize
示例5: AbstractReadyDecorator
# 需要导入模块: from sortedcontainers import SortedSet [as 别名]
# 或者: from sortedcontainers.SortedSet import remove [as 别名]
#.........这里部分代码省略.........
def check_tick_against_sync_point(tick):
if not self._pending_syncpoints:
return True # no more sync points
next_sync_point = self._pending_syncpoints[0]
if tick < next_sync_point:
# `tick` is not a sync_point and must run
# before the next sync_point.
return True
elif tick == next_sync_point:
# `tick` is the sync_point
if self._syncpoint_run_last and self._pending_ticks[0] < next_sync_point:
# There are still unfinished tasks that have to run
# before it.
return False
else:
# It is time to run the sync_point.
return True
else: # tick > next_sync_point
# has to wait til the sync_point completed
return False
tick = next(iter(self._queue), None)
if tick is not None:
if not check_tick_against_sync_point(tick):
return None
props = self.g.get_task_properties(tick)
if props.get(self._collected_prop, False):
raise ValueError("Task %s became ready twice." % tick)
self.g.set_task_property(tick, self._collected_prop, True)
self._queue.remove(tick)
return tick
def was_collected(self, tick):
"""
Returns if the given tick was collected.
"""
props = self.g.get_task_properties(tick)
return props.get(self._collected_prop, False)
def add_task(self, tick, task, properties={}):
properties = dict(properties)
properties[self._count_prop] = 0
properties[self._ready_prop] = 0
properties[self._collected_prop] = False
self.g.add_task(tick, task, properties=properties)
self._consider(tick)
self._pending_ticks.add(tick)
if properties.get("syncpoint", False):
self._pending_syncpoints.add(tick)
def remove_task(self, tick):
self.g.remove_task(tick)
if tick in self._queue:
self._queue.remove(tick)
if tick in self._pending_syncpoints:
self._pending_syncpoints.remove(tick)
if tick in self._pending_ticks:
self._pending_ticks.remove(tick)
示例6: test_remove
# 需要导入模块: from sortedcontainers import SortedSet [as 别名]
# 或者: from sortedcontainers.SortedSet import remove [as 别名]
def test_remove():
temp = SortedSet(range(0, 100), load=7)
temp.remove(50)
示例7: Chunk
# 需要导入模块: from sortedcontainers import SortedSet [as 别名]
# 或者: from sortedcontainers.SortedSet import remove [as 别名]
#.........这里部分代码省略.........
return filter(lambda t: self in t.chunks, self.feature.tests)
def modify(self, random):
feature_chunks = self.feature.chunks - {self}
system_chunks = set(self.feature.software_system.chunks.difference(self.feature.chunks))
self._add_dependencies(random, system_chunks, self.probability_gain_system_dependency)
self._add_dependencies(random, feature_chunks, self.probability_gain_feature_dependency)
self.local_content = random.create_local_content()
self._insert_bugs(random)
def merge(self, source_chunk, random):
for dependency in source_chunk.dependencies:
working_copy_dependency = self.feature.software_system.get_chunk(dependency.fully_qualified_name)
self.dependencies.add(working_copy_dependency)
self.modify(random)
def overwrite_with(self, source_chunk):
self.local_content = source_chunk.local_content
self.bugs.clear()
for old_bug in source_chunk.bugs:
new_bug = self.get_bug(old_bug.logical_name)
if new_bug is None:
self.add_bug(old_bug.logical_name)
self.dependencies.clear()
for dependency in source_chunk.dependencies:
new_dependency = self.feature.software_system.get_chunk(dependency.fully_qualified_name)
self.dependencies.add(new_dependency)
def _add_dependencies(self, random, candidate_chunks, threshold):
for candidate in SortedSet(candidate_chunks, key=lambda c: c.logical_name):
if random.dependency_should_be_added(threshold):
self.add_dependency(candidate)
def add_dependency(self, candidate):
self.dependencies.add(candidate)
def _insert_bugs(self, random):
while random.a_bug_should_be_inserted(self):
self.add_bug(self.bug_count)
self.bug_count += 1
def add_bug(self, logical_name):
self.bugs.add(Bug(logical_name, self))
def get_bug(self, logical_name):
result = filter(lambda bug: bug.logical_name == logical_name, self.bugs)
if len(result) is 0:
return None
else:
return result[0]
def refactor(self, random):
to_remove = set()
for dependency in self.dependencies:
if random.dependency_should_be_removed(self, dependency):
to_remove.add(dependency)
self.dependencies.difference_update(to_remove)
def debug(self, random, bug=None):
if len(self.bugs) == 0:
return False
if bug is None or bug not in self.bugs:
if random.unknown_bug_should_be_removed(self):
bug = random.choose_bug(self)
self.bugs.remove(bug)
elif random.known_bug_should_be_removed(self):
self.bugs.remove(bug)
def operate(self, random):
for bug in self.bugs_in_dependencies.union(self.bugs):
bug.manifest(random)
def __str__(self):
def string_repr_set(iterable):
return ",".join(map(lambda e: repr(e), iterable))
feature_dependencies = string_repr_set(filter(lambda c: c.feature == self.feature, self.dependencies))
system_dependencies = string_repr_set(filter(lambda c: c.feature != self.feature, self.dependencies))
bugs = ", ".join(map(lambda bug: str(bug), self.bugs))
return "c_%s:[%s]:[%s]->(in[%s],ex[%s])" % \
(str(self.logical_name), self.local_content, bugs, feature_dependencies, system_dependencies)
@property
def fully_qualified_name(self):
return "%s.%s" % (str(self.feature.logical_name), str(self.logical_name))
def __repr__(self):
return "c%s" % str(self.fully_qualified_name)
示例8: test_remove
# 需要导入模块: from sortedcontainers import SortedSet [as 别名]
# 或者: from sortedcontainers.SortedSet import remove [as 别名]
def test_remove():
temp = SortedSet(range(0, 100))
temp._reset(7)
temp.remove(50)
示例9: Selection
# 需要导入模块: from sortedcontainers import SortedSet [as 别名]
# 或者: from sortedcontainers.SortedSet import remove [as 别名]
class Selection(IMutableGSlice):
def __init__(
self,
universe: slice,
revealed: list = None,
intervals: Iterator = None,
_length: Optional[int] = None # For performance
):
#assert isinstance(universe, slice) # Should universe even be visible/exist?
#assert universe.start == 0
#assert isinstance(universe.stop, int)
#assert universe.stop >= 1 # TODO Do we need this?
self.universe = universe
if intervals is None and revealed is None:
self._intervals = self.revealed2sortedset([slice(0, universe.stop)])
elif intervals is not None:
self._intervals = SortedSet(intervals)
else:
self._intervals = self.revealed2sortedset(revealed)
self._revealed_count = _length if isinstance(_length, int) else Selection._compute_len(self._intervals)
@staticmethod
def revealed2sortedset(revealed: List[Union[tuple, slice]]) -> SortedSet:
""" Converts a list of included pairs to a sorted set of integers in O(n), n = size of @slices.
Every number from every slice is added to the sorted set, except 0.
"""
# 10, [] -> 10, []
# 10, [(0, 10)] -> 10, [10]
# 10, [(0, 7)] -> 10, [7]
# 10, [(7, 10)] -> 10, [7, 10]
# 10, [(3, 7)] -> 10, [3, 7]
# 10, [(0, 3), (7, 10)] -> 10, [3, 7, 10]
# 10, [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)] -> 10, [1, 2, 3, 4, 5, 6, 7, 8, 9]
try:
#intervals = SortedSet(a for a, _ in revealed).union(b for _, b in revealed)
intervals = SortedSet()
for a, b in revealed:
intervals.add(a)
intervals.add(b)
except TypeError: # slice
intervals = SortedSet(sl.start for sl in revealed).union(sl.stop for sl in revealed)
if 0 in intervals:
intervals.remove(0)
return intervals
@staticmethod
def sortedset2slices(sortedset: SortedSet) -> List[slice]:
""" Converts a sorted set of integers to a list of included slices in O(n), n = size of @sortedset.
If there is an even number of elements in @sortedset, the first slice is formed by the first and second
numbers, the second slice is formed by the third and fourth numbers, and so on.
If there is an odd number of elements in @sortedset, the pair consisting of the number 0 and the first element
in @sortedset becomes the first slice in the output list. The remaining slices, if any, are formed by the
second and third numbers, the fourth and fifth numbers, and so on.
"""
slices = []
if len(sortedset) % 2 == 0:
for i in range(0, len(sortedset), 2):
slices.append(slice(sortedset[i], sortedset[i + 1]))
else:
slices.append(slice(0, sortedset[0]))
for i in range(1, len(sortedset), 2):
slices.append(slice(sortedset[i], sortedset[i + 1]))
return slices
def slices(self) -> List[slice]:
return self.sortedset2slices(self._intervals)
def pairs(self) -> Iterator[Tuple[int, int]]:
if len(self._intervals) % 2 == 0:
return zip(self._intervals[::2], self._intervals[1::2])
return itertools.chain([(0, self._intervals[0])], zip(self._intervals[1::2], self._intervals[2::2]))
def gap_pairs(self) -> Iterator[Tuple[int, int]]:
return self.complement().pairs()
def intervals(self):
return self._intervals
def exclude(self, from_index: Optional[int], to_index: Optional[int]):
original_length = self._revealed_count
if isinstance(from_index, int) and -self.universe.stop <= from_index < 0:
from_index = from_index % self.universe.stop
if isinstance(to_index, int):
if to_index > self.universe.stop:
return self.exclude(from_index, None)
if -self.universe.stop <= to_index < 0:
to_index = to_index % self.universe.stop
assert from_index is None or self.universe.start <= from_index <= self.universe.stop
assert to_index is None or self.universe.start <= to_index <= self.universe.stop
if from_index is None:
from_index = self.universe.start
if to_index is None:
to_index = self.universe.stop
if len(self._intervals) == 0:
return 0
if from_index >= to_index:
return 0
m = self._intervals.bisect_right(from_index)
#.........这里部分代码省略.........
示例10: cluster_
# 需要导入模块: from sortedcontainers import SortedSet [as 别名]
# 或者: from sortedcontainers.SortedSet import remove [as 别名]
def cluster_(self, fX):
"""Compute complete dendrogram
Parameters
----------
fX : (n_items, dimension) np.array
Embeddings.
Returns
-------
dendrogram : list of (i, j, distance) tuples
Dendrogram.
"""
N = len(fX)
# clusters contain the identifier of each cluster
clusters = SortedSet(np.arange(N))
# labels[i] = c means ith item belongs to cluster c
labels = np.array(np.arange(N))
squared = squareform(pdist(fX, metric=self.metric))
distances = ValueSortedDict()
for i, j in itertools.combinations(range(N), 2):
distances[i, j] = squared[i, j]
dendrogram = []
for _ in range(N-1):
# find most similar clusters
(c_i, c_j), d = distances.peekitem(index=0)
# keep track of this iteration
dendrogram.append((c_i, c_j, d))
# index of clusters in 'clusters' and 'fX'
i = clusters.index(c_i)
j = clusters.index(c_j)
# merge items of cluster c_j into cluster c_i
labels[labels == c_j] = c_i
# update c_i representative
fX[i] += fX[j]
# remove c_j cluster
fX[j:-1, :] = fX[j+1:, :]
fX = fX[:-1]
# remove distances to c_j cluster
for c in clusters[:j]:
distances.pop((c, c_j))
for c in clusters[j+1:]:
distances.pop((c_j, c))
clusters.remove(c_j)
if len(clusters) < 2:
continue
# compute distance to new c_i cluster
new_d = cdist(fX[i, :].reshape((1, -1)), fX, metric=self.metric).squeeze()
for c_k, d in zip(clusters, new_d):
if c_k < c_i:
distances[c_k, c_i] = d
elif c_k > c_i:
distances[c_i, c_k] = d
return dendrogram