本文整理汇总了Python中sortedcontainers.SortedDict.itervalues方法的典型用法代码示例。如果您正苦于以下问题:Python SortedDict.itervalues方法的具体用法?Python SortedDict.itervalues怎么用?Python SortedDict.itervalues使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sortedcontainers.SortedDict
的用法示例。
在下文中一共展示了SortedDict.itervalues方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: arrayRDP
# 需要导入模块: from sortedcontainers import SortedDict [as 别名]
# 或者: from sortedcontainers.SortedDict import itervalues [as 别名]
def arrayRDP(arr, epsilon=0.0, n=None):
"""
This is a slightly modified version of the _aRDP function, that accepts
as arguments the tolerance in the distance and the maximum number of points
the algorithm can select.
**Note:** The results of this algoritm should be identical to the arrayRDP
function if the *n* parameter is not specified. In that case, the
performance is slightly worse, although the asymptotic complexity is the
same. For this reason, this function internally delegates the solution in
that function if the *n* parameter is missing.
Parameters
----------
arr:
Array of values of consecutive points.
epsilon:
Maximum difference allowed in the simplification process.
n:
Maximum number of points of the resulted simplificated array.
Returns
-------
out:
Array of indices of the selected points.
"""
if n is None:
return _aRDP(arr, epsilon)
if epsilon <= 0.0:
raise ValueError('Epsilon must be > 0.0')
n = n or len(arr)
if n < 3:
return arr
fragments = SortedDict()
#We store the distances as negative values due to the default order of
#sorteddict
dist, idx = max_vdist(arr, 0, len(arr) - 1)
fragments[(-dist, idx)] = (0, len(arr) - 1)
while len(fragments) < n-1:
(dist, idx), (first, last) = fragments.popitem(last=False)
if -dist <= epsilon:
#We have to put again the last item to prevent loss
fragments[(dist, idx)] = (first, last)
break
else:
#We have to break the fragment in the selected index
dist, newidx = max_vdist(arr, first, idx)
fragments[(-dist, newidx)] = (first, idx)
dist, newidx = max_vdist(arr, idx, last)
fragments[(-dist, newidx)] = (idx, last)
#Now we have to get all the indices in the keys of the fragments in order.
result = SortedList(i[0] for i in fragments.itervalues())
result.add(len(arr) - 1)
return np.array(result)
示例2: TreePage
# 需要导入模块: from sortedcontainers import SortedDict [as 别名]
# 或者: from sortedcontainers.SortedDict import itervalues [as 别名]
class TreePage(BasePage):
"""
Page object, implemented with a sorted dict. Who knows what's underneath!
"""
def __init__(self, *args, **kwargs):
storage = kwargs.pop("storage", None)
super(TreePage, self).__init__(*args, **kwargs)
self._storage = SortedDict() if storage is None else storage
def keys(self):
if len(self._storage) == 0:
return set()
else:
return set.union(*(set(range(*self._resolve_range(mo))) for mo in self._storage.itervalues()))
def replace_mo(self, state, old_mo, new_mo):
start, end = self._resolve_range(old_mo)
for key in self._storage.irange(start, end-1):
val = self._storage[key]
if val is old_mo:
#assert new_mo.includes(a)
self._storage[key] = new_mo
def store_overwrite(self, state, new_mo, start, end):
# iterate over each item we might overwrite
# track our mutations separately since we're in the process of iterating
deletes = []
updates = { start: new_mo }
for key in self._storage.irange(maximum=end-1, reverse=True):
old_mo = self._storage[key]
# make sure we aren't overwriting all of an item that overlaps the end boundary
if end < self._page_addr + self._page_size and end not in updates and old_mo.includes(end):
updates[end] = old_mo
# we can't set a minimum on the range because we need to do the above for
# the first object before start too
if key < start:
break
# delete any key that falls within the range
deletes.append(key)
#assert all(m.includes(i) for i,m in updates.items())
# perform mutations
for key in deletes:
del self._storage[key]
self._storage.update(updates)
def store_underwrite(self, state, new_mo, start, end):
# track the point that we need to write up to
last_missing = end - 1
# track also updates since we can't update while iterating
updates = {}
for key in self._storage.irange(maximum=end-1, reverse=True):
mo = self._storage[key]
# if the mo stops
if mo.base <= last_missing and not mo.includes(last_missing):
updates[max(mo.last_addr+1, start)] = new_mo
last_missing = mo.base - 1
# we can't set a minimum on the range because we need to do the above for
# the first object before start too
if last_missing < start:
break
# if there are no memory objects <= start, we won't have filled start yet
if last_missing >= start:
updates[start] = new_mo
#assert all(m.includes(i) for i,m in updates.items())
self._storage.update(updates)
def load_mo(self, state, page_idx):
"""
Loads a memory object from memory.
:param page_idx: the index into the page
:returns: a tuple of the object
"""
try:
key = next(self._storage.irange(maximum=page_idx, reverse=True))
except StopIteration:
return None
else:
return self._storage[key]
def load_slice(self, state, start, end):
"""
Return the memory objects overlapping with the provided slice.
:param start: the start address
#.........这里部分代码省略.........
示例3: test_itervalues
# 需要导入模块: from sortedcontainers import SortedDict [as 别名]
# 或者: from sortedcontainers.SortedDict import itervalues [as 别名]
def test_itervalues():
mapping = [(val, pos) for pos, val in enumerate(string.ascii_lowercase)]
temp = SortedDict(mapping)
assert list(temp.itervalues()) == [pos for key, pos in mapping]
示例4: TxGraph
# 需要导入模块: from sortedcontainers import SortedDict [as 别名]
# 或者: from sortedcontainers.SortedDict import itervalues [as 别名]
class TxGraph(object):
"""represents a graph of all transactions
within the current window
Attributes:
median(float) : the current median of the degree of the nodes
highMarker(int) : the latest timestamp seen so far
lowMarker(int) : the earliest timestamp of the window we are
interested in
txMap(dict) : this is a collection of EdgeList's with key being
the timestamp and the value an instance of EdgeList
edgeMap(dict) : this is collection of all Edges within a window
with key being the name of an Edge
nodeMap(dict) : this represents a collection of Nodes with a window
with key being the name of the Node
degreeList(list): list of degrees of noded (sorted)
"""
WINDOW_SIZE = 60
def __init__(self):
self.median = 0
self.highMarker = TxGraph.WINDOW_SIZE
self.lowMarker = 1
self.txMap = SortedDict() #sorted by unix epoch (timestamp)
self.edgeMap = SortedDict() #sorted by edge name
self.nodeMap = SortedDict() #sorted by node name
self.degreeList = SortedList() #sorted by degreeList
def __calculate_median(self, use_existing_list=False):
"""calculates median by adding degrees to a sortedlist
"""
if not use_existing_list:
#lets reconstruct the list
self.degreeList = SortedList()
for node in self.nodeMap.itervalues():
if node.degree > 0:
self.degreeList.add(node.degree)
listLen = len(self.degreeList)
if listLen == 0:
raise Exception("No items in the degreeList")
if listLen == 1:
return self.degreeList[0]/1.0
if (listLen % 2) == 0:
return (self.degreeList[listLen/2] + self.degreeList[(listLen/2) - 1]) / 2.0
return self.degreeList[listLen/2]/1.0
def __get_edgelist(self, tstamp, create=True):
"""returns an instance of EdgeList with matching
timestamp and creates one if needed
"""
edgeList = self.txMap.get(tstamp, None)
if edgeList is None and create is True:
edgeList = EdgeList(tstamp)
self.txMap[tstamp] = edgeList
return edgeList
def __getnode_with_name(self, name, create=True):
"""returns an instance of Node with matching name
and creates one if necessary
Args:
name(str) : name of the edge
create(bool): flag to indicate whether to create a
missing node
"""
node = self.nodeMap.get(name, None)
if node is None and create is True:
node = Node(name)
self.nodeMap[name] = node
return node
def __incr_degree_of_edge_nodes(self, edge):
"""increments the degree of the two nodes
of an edge
"""
src = self.__getnode_with_name(edge.source)
src.incr_degree()
tar = self.__getnode_with_name(edge.target)
tar.incr_degree()
return (src.degree, tar.degree)
def __decr_degree_of_edge_nodes(self, edge):
"""decrements the degree of the two nodes
of an edge
"""
self.__decr_degree_of_node(edge.source)
self.__decr_degree_of_node(edge.target)
#.........这里部分代码省略.........
示例5: OrderedSet
# 需要导入模块: from sortedcontainers import SortedDict [as 别名]
# 或者: from sortedcontainers.SortedDict import itervalues [as 别名]
class OrderedSet(co.MutableSet, co.Sequence):
"""Like OrderedDict, OrderedSet maintains the insertion order of elements.
For example::
>>> ordered_set = OrderedSet('abcde')
>>> list(ordered_set) == list('abcde')
>>> ordered_set = OrderedSet('edcba')
>>> list(ordered_set) == list('edcba')
OrderedSet also implements the collections.Sequence interface.
"""
def __init__(self, iterable=()):
self._keys = {}
self._nums = SortedDict()
self._count = count()
self |= iterable
def __contains__(self, key):
"``key in ordered_set``"
return key in self._keys
count = __contains__
def __iter__(self):
"``iter(ordered_set)``"
return self._nums.itervalues()
def __reversed__(self):
"``reversed(ordered_set)``"
_nums = self._nums
for key in reversed(_nums):
yield _nums[key]
def __getitem__(self, index):
"``ordered_set[index]`` -> element; lookup element at index."
_nums = self._nums
num = _nums.iloc[index]
return _nums[num]
def __len__(self):
"``len(ordered_set)``"
return len(self._keys)
def index(self, key):
"Return index of key."
try:
return self._keys[key]
except KeyError:
raise ValueError('%r is not in %s' % (key, type(self).__name__))
def add(self, key):
"Add element, key, to set."
if key not in self._keys:
num = next(self._count)
self._keys[key] = num
self._nums[num] = key
def discard(self, key):
"Remove element, key, from set if it is a member."
num = self._keys.pop(key, None)
if num is not None:
del self._nums[num]
def __repr__(self):
"Text representation of set."
return '%s(%r)' % (type(self).__name__, list(self))
__str__ = __repr__
示例6: DotMap
# 需要导入模块: from sortedcontainers import SortedDict [as 别名]
# 或者: from sortedcontainers.SortedDict import itervalues [as 别名]
#.........这里部分代码省略.........
d[k] = v
return d
def pprint(self):
pprint(self.to_dict())
# proper dict subclassing
def values(self):
return self._map.values()
@staticmethod
def parse_other(other):
if type(other) is DotMap:
return other._map
else:
return other
def __cmp__(self, other):
other = DotMap.parse_other(other)
return self._map.__cmp__(other)
def __eq__(self, other):
other = DotMap.parse_other(other)
if not isinstance(other, dict):
return False
return self._map.__eq__(other)
def __ge__(self, other):
other = DotMap.parse_other(other)
return self._map.__ge__(other)
def __gt__(self, other):
other = DotMap.parse_other(other)
return self._map.__gt__(other)
def __le__(self, other):
other = DotMap.parseOther(other)
return self._map.__le__(other)
def __lt__(self, other):
other = DotMap.parse_other(other)
return self._map.__lt__(other)
def __ne__(self, other):
other = DotMap.parse_other(other)
return self._map.__ne__(other)
def __delitem__(self, key):
return self._map.__delitem__(key)
def __len__(self):
return self._map.__len__()
def copy(self):
return self
def get(self, key, default=None):
return self._map.get(key, default)
def has_key(self, key):
return key in self._map
def iterkeys(self):
return self._map.iterkeys()
def itervalues(self):
return self._map.itervalues()
def keys(self):
return self._map.keys()
def pop(self, key, default=None):
return self._map.pop(key, default)
def setdefault(self, key, default=None):
return self._map.setdefault(key, default)
def viewitems(self):
if version_info.major == 2 and version_info.minor >= 7:
return self._map.viewitems()
else:
return self._map.items()
def viewkeys(self):
if version_info.major == 2 and version_info.minor >= 7:
return self._map.viewkeys()
else:
return self._map.keys()
def viewvalues(self):
if version_info.major == 2 and version_info.minor >= 7:
return self._map.viewvalues()
else:
return self._map.values()
@classmethod
def fromkeys(cls, seq, value=None):
d = DotMap()
d._map = SortedDict.fromkeys(seq, value)
return d
示例7: KeyedRegion
# 需要导入模块: from sortedcontainers import SortedDict [as 别名]
# 或者: from sortedcontainers.SortedDict import itervalues [as 别名]
class KeyedRegion(object):
"""
KeyedRegion keeps a mapping between stack offsets and all variables covering that offset. It assumes no variable in
this region overlap with another variable in this region.
Registers and function frames can all be viewed as a keyed region.
"""
def __init__(self, tree=None):
self._storage = SortedDict() if tree is None else tree
def _get_container(self, offset):
try:
base_offset = next(self._storage.irange(maximum=offset, reverse=True))
except StopIteration:
return offset, None
else:
container = self._storage[base_offset]
if container.includes(offset):
return base_offset, container
return offset, None
def __contains__(self, offset):
"""
Test if there is at least one varaible covering the given offset.
:param offset:
:return:
"""
return self._get_container(offset)[1] is not None
def __len__(self):
return len(self._storage)
def __iter__(self):
return self._storage.itervalues()
def __eq__(self, other):
if set(self._storage.keys()) != set(other._storage.keys()):
return False
for k, v in self._storage.iteritems():
if v != other._storage[k]:
return False
return True
def copy(self):
if not self._storage:
return KeyedRegion()
kr = KeyedRegion()
for key, ro in self._storage.iteritems():
kr._storage[key] = ro.copy()
return kr
def merge(self, other, make_phi_func=None):
"""
Merge another KeyedRegion into this KeyedRegion.
:param KeyedRegion other: The other instance to merge with.
:return: None
"""
# TODO: is the current solution not optimal enough?
for _, item in other._storage.iteritems(): # type: RegionObject
for loc_and_var in item.objects:
self.__store(loc_and_var, overwrite=False, make_phi_func=make_phi_func)
return self
def dbg_repr(self):
"""
Get a debugging representation of this keyed region.
:return: A string of debugging output.
"""
keys = self._storage.keys()
offset_to_vars = { }
for key in sorted(keys):
ro = self._storage[key]
variables = [ obj.variable for obj in ro.objects ]
offset_to_vars[key] = variables
s = [ ]
for offset, variables in offset_to_vars.iteritems():
s.append("Offset %#x: %s" % (offset, variables))
return "\n".join(s)
def add_variable(self, start, variable):
"""
Add a variable to this region at the given offset.
:param int start:
:param SimVariable variable:
:return: None
"""
self._store(start, variable, overwrite=False)
#.........这里部分代码省略.........