Edit File by line
/home/barbar84/public_h.../wp-conte.../plugins/sujqvwi/AnonR/anonr.TX.../opt/imh-pyth.../lib/python2....
File: collections.py
'''This module implements specialized container datatypes providing
[0] Fix | Delete
alternatives to Python's general purpose built-in containers, dict,
[1] Fix | Delete
list, set, and tuple.
[2] Fix | Delete
[3] Fix | Delete
* namedtuple factory function for creating tuple subclasses with named fields
[4] Fix | Delete
* deque list-like container with fast appends and pops on either end
[5] Fix | Delete
* Counter dict subclass for counting hashable objects
[6] Fix | Delete
* OrderedDict dict subclass that remembers the order entries were added
[7] Fix | Delete
* defaultdict dict subclass that calls a factory function to supply missing values
[8] Fix | Delete
[9] Fix | Delete
'''
[10] Fix | Delete
[11] Fix | Delete
__all__ = ['Counter', 'deque', 'defaultdict', 'namedtuple', 'OrderedDict']
[12] Fix | Delete
# For bootstrapping reasons, the collection ABCs are defined in _abcoll.py.
[13] Fix | Delete
# They should however be considered an integral part of collections.py.
[14] Fix | Delete
from _abcoll import *
[15] Fix | Delete
import _abcoll
[16] Fix | Delete
__all__ += _abcoll.__all__
[17] Fix | Delete
[18] Fix | Delete
from _collections import deque, defaultdict
[19] Fix | Delete
from operator import itemgetter as _itemgetter, eq as _eq
[20] Fix | Delete
from keyword import iskeyword as _iskeyword
[21] Fix | Delete
import sys as _sys
[22] Fix | Delete
import heapq as _heapq
[23] Fix | Delete
from itertools import repeat as _repeat, chain as _chain, starmap as _starmap
[24] Fix | Delete
from itertools import imap as _imap
[25] Fix | Delete
[26] Fix | Delete
try:
[27] Fix | Delete
from thread import get_ident as _get_ident
[28] Fix | Delete
except ImportError:
[29] Fix | Delete
from dummy_thread import get_ident as _get_ident
[30] Fix | Delete
[31] Fix | Delete
[32] Fix | Delete
################################################################################
[33] Fix | Delete
### OrderedDict
[34] Fix | Delete
################################################################################
[35] Fix | Delete
[36] Fix | Delete
class OrderedDict(dict):
[37] Fix | Delete
'Dictionary that remembers insertion order'
[38] Fix | Delete
# An inherited dict maps keys to values.
[39] Fix | Delete
# The inherited dict provides __getitem__, __len__, __contains__, and get.
[40] Fix | Delete
# The remaining methods are order-aware.
[41] Fix | Delete
# Big-O running times for all methods are the same as regular dictionaries.
[42] Fix | Delete
[43] Fix | Delete
# The internal self.__map dict maps keys to links in a doubly linked list.
[44] Fix | Delete
# The circular doubly linked list starts and ends with a sentinel element.
[45] Fix | Delete
# The sentinel element never gets deleted (this simplifies the algorithm).
[46] Fix | Delete
# Each link is stored as a list of length three: [PREV, NEXT, KEY].
[47] Fix | Delete
[48] Fix | Delete
def __init__(*args, **kwds):
[49] Fix | Delete
'''Initialize an ordered dictionary. The signature is the same as
[50] Fix | Delete
regular dictionaries, but keyword arguments are not recommended because
[51] Fix | Delete
their insertion order is arbitrary.
[52] Fix | Delete
[53] Fix | Delete
'''
[54] Fix | Delete
if not args:
[55] Fix | Delete
raise TypeError("descriptor '__init__' of 'OrderedDict' object "
[56] Fix | Delete
"needs an argument")
[57] Fix | Delete
self = args[0]
[58] Fix | Delete
args = args[1:]
[59] Fix | Delete
if len(args) > 1:
[60] Fix | Delete
raise TypeError('expected at most 1 arguments, got %d' % len(args))
[61] Fix | Delete
try:
[62] Fix | Delete
self.__root
[63] Fix | Delete
except AttributeError:
[64] Fix | Delete
self.__root = root = [] # sentinel node
[65] Fix | Delete
root[:] = [root, root, None]
[66] Fix | Delete
self.__map = {}
[67] Fix | Delete
self.__update(*args, **kwds)
[68] Fix | Delete
[69] Fix | Delete
def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
[70] Fix | Delete
'od.__setitem__(i, y) <==> od[i]=y'
[71] Fix | Delete
# Setting a new item creates a new link at the end of the linked list,
[72] Fix | Delete
# and the inherited dictionary is updated with the new key/value pair.
[73] Fix | Delete
if key not in self:
[74] Fix | Delete
root = self.__root
[75] Fix | Delete
last = root[0]
[76] Fix | Delete
last[1] = root[0] = self.__map[key] = [last, root, key]
[77] Fix | Delete
return dict_setitem(self, key, value)
[78] Fix | Delete
[79] Fix | Delete
def __delitem__(self, key, dict_delitem=dict.__delitem__):
[80] Fix | Delete
'od.__delitem__(y) <==> del od[y]'
[81] Fix | Delete
# Deleting an existing item uses self.__map to find the link which gets
[82] Fix | Delete
# removed by updating the links in the predecessor and successor nodes.
[83] Fix | Delete
dict_delitem(self, key)
[84] Fix | Delete
link_prev, link_next, _ = self.__map.pop(key)
[85] Fix | Delete
link_prev[1] = link_next # update link_prev[NEXT]
[86] Fix | Delete
link_next[0] = link_prev # update link_next[PREV]
[87] Fix | Delete
[88] Fix | Delete
def __iter__(self):
[89] Fix | Delete
'od.__iter__() <==> iter(od)'
[90] Fix | Delete
# Traverse the linked list in order.
[91] Fix | Delete
root = self.__root
[92] Fix | Delete
curr = root[1] # start at the first node
[93] Fix | Delete
while curr is not root:
[94] Fix | Delete
yield curr[2] # yield the curr[KEY]
[95] Fix | Delete
curr = curr[1] # move to next node
[96] Fix | Delete
[97] Fix | Delete
def __reversed__(self):
[98] Fix | Delete
'od.__reversed__() <==> reversed(od)'
[99] Fix | Delete
# Traverse the linked list in reverse order.
[100] Fix | Delete
root = self.__root
[101] Fix | Delete
curr = root[0] # start at the last node
[102] Fix | Delete
while curr is not root:
[103] Fix | Delete
yield curr[2] # yield the curr[KEY]
[104] Fix | Delete
curr = curr[0] # move to previous node
[105] Fix | Delete
[106] Fix | Delete
def clear(self):
[107] Fix | Delete
'od.clear() -> None. Remove all items from od.'
[108] Fix | Delete
root = self.__root
[109] Fix | Delete
root[:] = [root, root, None]
[110] Fix | Delete
self.__map.clear()
[111] Fix | Delete
dict.clear(self)
[112] Fix | Delete
[113] Fix | Delete
# -- the following methods do not depend on the internal structure --
[114] Fix | Delete
[115] Fix | Delete
def keys(self):
[116] Fix | Delete
'od.keys() -> list of keys in od'
[117] Fix | Delete
return list(self)
[118] Fix | Delete
[119] Fix | Delete
def values(self):
[120] Fix | Delete
'od.values() -> list of values in od'
[121] Fix | Delete
return [self[key] for key in self]
[122] Fix | Delete
[123] Fix | Delete
def items(self):
[124] Fix | Delete
'od.items() -> list of (key, value) pairs in od'
[125] Fix | Delete
return [(key, self[key]) for key in self]
[126] Fix | Delete
[127] Fix | Delete
def iterkeys(self):
[128] Fix | Delete
'od.iterkeys() -> an iterator over the keys in od'
[129] Fix | Delete
return iter(self)
[130] Fix | Delete
[131] Fix | Delete
def itervalues(self):
[132] Fix | Delete
'od.itervalues -> an iterator over the values in od'
[133] Fix | Delete
for k in self:
[134] Fix | Delete
yield self[k]
[135] Fix | Delete
[136] Fix | Delete
def iteritems(self):
[137] Fix | Delete
'od.iteritems -> an iterator over the (key, value) pairs in od'
[138] Fix | Delete
for k in self:
[139] Fix | Delete
yield (k, self[k])
[140] Fix | Delete
[141] Fix | Delete
update = MutableMapping.update
[142] Fix | Delete
[143] Fix | Delete
__update = update # let subclasses override update without breaking __init__
[144] Fix | Delete
[145] Fix | Delete
__marker = object()
[146] Fix | Delete
[147] Fix | Delete
def pop(self, key, default=__marker):
[148] Fix | Delete
'''od.pop(k[,d]) -> v, remove specified key and return the corresponding
[149] Fix | Delete
value. If key is not found, d is returned if given, otherwise KeyError
[150] Fix | Delete
is raised.
[151] Fix | Delete
[152] Fix | Delete
'''
[153] Fix | Delete
if key in self:
[154] Fix | Delete
result = self[key]
[155] Fix | Delete
del self[key]
[156] Fix | Delete
return result
[157] Fix | Delete
if default is self.__marker:
[158] Fix | Delete
raise KeyError(key)
[159] Fix | Delete
return default
[160] Fix | Delete
[161] Fix | Delete
def setdefault(self, key, default=None):
[162] Fix | Delete
'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
[163] Fix | Delete
if key in self:
[164] Fix | Delete
return self[key]
[165] Fix | Delete
self[key] = default
[166] Fix | Delete
return default
[167] Fix | Delete
[168] Fix | Delete
def popitem(self, last=True):
[169] Fix | Delete
'''od.popitem() -> (k, v), return and remove a (key, value) pair.
[170] Fix | Delete
Pairs are returned in LIFO order if last is true or FIFO order if false.
[171] Fix | Delete
[172] Fix | Delete
'''
[173] Fix | Delete
if not self:
[174] Fix | Delete
raise KeyError('dictionary is empty')
[175] Fix | Delete
key = next(reversed(self) if last else iter(self))
[176] Fix | Delete
value = self.pop(key)
[177] Fix | Delete
return key, value
[178] Fix | Delete
[179] Fix | Delete
def __repr__(self, _repr_running={}):
[180] Fix | Delete
'od.__repr__() <==> repr(od)'
[181] Fix | Delete
call_key = id(self), _get_ident()
[182] Fix | Delete
if call_key in _repr_running:
[183] Fix | Delete
return '...'
[184] Fix | Delete
_repr_running[call_key] = 1
[185] Fix | Delete
try:
[186] Fix | Delete
if not self:
[187] Fix | Delete
return '%s()' % (self.__class__.__name__,)
[188] Fix | Delete
return '%s(%r)' % (self.__class__.__name__, self.items())
[189] Fix | Delete
finally:
[190] Fix | Delete
del _repr_running[call_key]
[191] Fix | Delete
[192] Fix | Delete
def __reduce__(self):
[193] Fix | Delete
'Return state information for pickling'
[194] Fix | Delete
items = [[k, self[k]] for k in self]
[195] Fix | Delete
inst_dict = vars(self).copy()
[196] Fix | Delete
for k in vars(OrderedDict()):
[197] Fix | Delete
inst_dict.pop(k, None)
[198] Fix | Delete
if inst_dict:
[199] Fix | Delete
return (self.__class__, (items,), inst_dict)
[200] Fix | Delete
return self.__class__, (items,)
[201] Fix | Delete
[202] Fix | Delete
def copy(self):
[203] Fix | Delete
'od.copy() -> a shallow copy of od'
[204] Fix | Delete
return self.__class__(self)
[205] Fix | Delete
[206] Fix | Delete
@classmethod
[207] Fix | Delete
def fromkeys(cls, iterable, value=None):
[208] Fix | Delete
'''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S.
[209] Fix | Delete
If not specified, the value defaults to None.
[210] Fix | Delete
[211] Fix | Delete
'''
[212] Fix | Delete
self = cls()
[213] Fix | Delete
for key in iterable:
[214] Fix | Delete
self[key] = value
[215] Fix | Delete
return self
[216] Fix | Delete
[217] Fix | Delete
def __eq__(self, other):
[218] Fix | Delete
'''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive
[219] Fix | Delete
while comparison to a regular mapping is order-insensitive.
[220] Fix | Delete
[221] Fix | Delete
'''
[222] Fix | Delete
if isinstance(other, OrderedDict):
[223] Fix | Delete
return dict.__eq__(self, other) and all(_imap(_eq, self, other))
[224] Fix | Delete
return dict.__eq__(self, other)
[225] Fix | Delete
[226] Fix | Delete
def __ne__(self, other):
[227] Fix | Delete
'od.__ne__(y) <==> od!=y'
[228] Fix | Delete
return not self == other
[229] Fix | Delete
[230] Fix | Delete
# -- the following methods support python 3.x style dictionary views --
[231] Fix | Delete
[232] Fix | Delete
def viewkeys(self):
[233] Fix | Delete
"od.viewkeys() -> a set-like object providing a view on od's keys"
[234] Fix | Delete
return KeysView(self)
[235] Fix | Delete
[236] Fix | Delete
def viewvalues(self):
[237] Fix | Delete
"od.viewvalues() -> an object providing a view on od's values"
[238] Fix | Delete
return ValuesView(self)
[239] Fix | Delete
[240] Fix | Delete
def viewitems(self):
[241] Fix | Delete
"od.viewitems() -> a set-like object providing a view on od's items"
[242] Fix | Delete
return ItemsView(self)
[243] Fix | Delete
[244] Fix | Delete
[245] Fix | Delete
################################################################################
[246] Fix | Delete
### namedtuple
[247] Fix | Delete
################################################################################
[248] Fix | Delete
[249] Fix | Delete
_class_template = '''\
[250] Fix | Delete
class {typename}(tuple):
[251] Fix | Delete
'{typename}({arg_list})'
[252] Fix | Delete
[253] Fix | Delete
__slots__ = ()
[254] Fix | Delete
[255] Fix | Delete
_fields = {field_names!r}
[256] Fix | Delete
[257] Fix | Delete
def __new__(_cls, {arg_list}):
[258] Fix | Delete
'Create new instance of {typename}({arg_list})'
[259] Fix | Delete
return _tuple.__new__(_cls, ({arg_list}))
[260] Fix | Delete
[261] Fix | Delete
@classmethod
[262] Fix | Delete
def _make(cls, iterable, new=tuple.__new__, len=len):
[263] Fix | Delete
'Make a new {typename} object from a sequence or iterable'
[264] Fix | Delete
result = new(cls, iterable)
[265] Fix | Delete
if len(result) != {num_fields:d}:
[266] Fix | Delete
raise TypeError('Expected {num_fields:d} arguments, got %d' % len(result))
[267] Fix | Delete
return result
[268] Fix | Delete
[269] Fix | Delete
def __repr__(self):
[270] Fix | Delete
'Return a nicely formatted representation string'
[271] Fix | Delete
return '{typename}({repr_fmt})' % self
[272] Fix | Delete
[273] Fix | Delete
def _asdict(self):
[274] Fix | Delete
'Return a new OrderedDict which maps field names to their values'
[275] Fix | Delete
return OrderedDict(zip(self._fields, self))
[276] Fix | Delete
[277] Fix | Delete
def _replace(_self, **kwds):
[278] Fix | Delete
'Return a new {typename} object replacing specified fields with new values'
[279] Fix | Delete
result = _self._make(map(kwds.pop, {field_names!r}, _self))
[280] Fix | Delete
if kwds:
[281] Fix | Delete
raise ValueError('Got unexpected field names: %r' % kwds.keys())
[282] Fix | Delete
return result
[283] Fix | Delete
[284] Fix | Delete
def __getnewargs__(self):
[285] Fix | Delete
'Return self as a plain tuple. Used by copy and pickle.'
[286] Fix | Delete
return tuple(self)
[287] Fix | Delete
[288] Fix | Delete
__dict__ = _property(_asdict)
[289] Fix | Delete
[290] Fix | Delete
def __getstate__(self):
[291] Fix | Delete
'Exclude the OrderedDict from pickling'
[292] Fix | Delete
pass
[293] Fix | Delete
[294] Fix | Delete
{field_defs}
[295] Fix | Delete
'''
[296] Fix | Delete
[297] Fix | Delete
_repr_template = '{name}=%r'
[298] Fix | Delete
[299] Fix | Delete
_field_template = '''\
[300] Fix | Delete
{name} = _property(_itemgetter({index:d}), doc='Alias for field number {index:d}')
[301] Fix | Delete
'''
[302] Fix | Delete
[303] Fix | Delete
def namedtuple(typename, field_names, verbose=False, rename=False):
[304] Fix | Delete
"""Returns a new subclass of tuple with named fields.
[305] Fix | Delete
[306] Fix | Delete
>>> Point = namedtuple('Point', ['x', 'y'])
[307] Fix | Delete
>>> Point.__doc__ # docstring for the new class
[308] Fix | Delete
'Point(x, y)'
[309] Fix | Delete
>>> p = Point(11, y=22) # instantiate with positional args or keywords
[310] Fix | Delete
>>> p[0] + p[1] # indexable like a plain tuple
[311] Fix | Delete
33
[312] Fix | Delete
>>> x, y = p # unpack like a regular tuple
[313] Fix | Delete
>>> x, y
[314] Fix | Delete
(11, 22)
[315] Fix | Delete
>>> p.x + p.y # fields also accessible by name
[316] Fix | Delete
33
[317] Fix | Delete
>>> d = p._asdict() # convert to a dictionary
[318] Fix | Delete
>>> d['x']
[319] Fix | Delete
11
[320] Fix | Delete
>>> Point(**d) # convert from a dictionary
[321] Fix | Delete
Point(x=11, y=22)
[322] Fix | Delete
>>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
[323] Fix | Delete
Point(x=100, y=22)
[324] Fix | Delete
[325] Fix | Delete
"""
[326] Fix | Delete
[327] Fix | Delete
# Validate the field names. At the user's option, either generate an error
[328] Fix | Delete
# message or automatically replace the field name with a valid name.
[329] Fix | Delete
if isinstance(field_names, basestring):
[330] Fix | Delete
field_names = field_names.replace(',', ' ').split()
[331] Fix | Delete
field_names = map(str, field_names)
[332] Fix | Delete
typename = str(typename)
[333] Fix | Delete
if rename:
[334] Fix | Delete
seen = set()
[335] Fix | Delete
for index, name in enumerate(field_names):
[336] Fix | Delete
if (not all(c.isalnum() or c=='_' for c in name)
[337] Fix | Delete
or _iskeyword(name)
[338] Fix | Delete
or not name
[339] Fix | Delete
or name[0].isdigit()
[340] Fix | Delete
or name.startswith('_')
[341] Fix | Delete
or name in seen):
[342] Fix | Delete
field_names[index] = '_%d' % index
[343] Fix | Delete
seen.add(name)
[344] Fix | Delete
for name in [typename] + field_names:
[345] Fix | Delete
if type(name) != str:
[346] Fix | Delete
raise TypeError('Type names and field names must be strings')
[347] Fix | Delete
if not all(c.isalnum() or c=='_' for c in name):
[348] Fix | Delete
raise ValueError('Type names and field names can only contain '
[349] Fix | Delete
'alphanumeric characters and underscores: %r' % name)
[350] Fix | Delete
if _iskeyword(name):
[351] Fix | Delete
raise ValueError('Type names and field names cannot be a '
[352] Fix | Delete
'keyword: %r' % name)
[353] Fix | Delete
if name[0].isdigit():
[354] Fix | Delete
raise ValueError('Type names and field names cannot start with '
[355] Fix | Delete
'a number: %r' % name)
[356] Fix | Delete
seen = set()
[357] Fix | Delete
for name in field_names:
[358] Fix | Delete
if name.startswith('_') and not rename:
[359] Fix | Delete
raise ValueError('Field names cannot start with an underscore: '
[360] Fix | Delete
'%r' % name)
[361] Fix | Delete
if name in seen:
[362] Fix | Delete
raise ValueError('Encountered duplicate field name: %r' % name)
[363] Fix | Delete
seen.add(name)
[364] Fix | Delete
[365] Fix | Delete
# Fill-in the class template
[366] Fix | Delete
class_definition = _class_template.format(
[367] Fix | Delete
typename = typename,
[368] Fix | Delete
field_names = tuple(field_names),
[369] Fix | Delete
num_fields = len(field_names),
[370] Fix | Delete
arg_list = repr(tuple(field_names)).replace("'", "")[1:-1],
[371] Fix | Delete
repr_fmt = ', '.join(_repr_template.format(name=name)
[372] Fix | Delete
for name in field_names),
[373] Fix | Delete
field_defs = '\n'.join(_field_template.format(index=index, name=name)
[374] Fix | Delete
for index, name in enumerate(field_names))
[375] Fix | Delete
)
[376] Fix | Delete
if verbose:
[377] Fix | Delete
print class_definition
[378] Fix | Delete
[379] Fix | Delete
# Execute the template string in a temporary namespace and support
[380] Fix | Delete
# tracing utilities by setting a value for frame.f_globals['__name__']
[381] Fix | Delete
namespace = dict(_itemgetter=_itemgetter, __name__='namedtuple_%s' % typename,
[382] Fix | Delete
OrderedDict=OrderedDict, _property=property, _tuple=tuple)
[383] Fix | Delete
try:
[384] Fix | Delete
exec class_definition in namespace
[385] Fix | Delete
except SyntaxError as e:
[386] Fix | Delete
raise SyntaxError(e.message + ':\n' + class_definition)
[387] Fix | Delete
result = namespace[typename]
[388] Fix | Delete
[389] Fix | Delete
# For pickling to work, the __module__ variable needs to be set to the frame
[390] Fix | Delete
# where the named tuple is created. Bypass this step in environments where
[391] Fix | Delete
# sys._getframe is not defined (Jython for example) or sys._getframe is not
[392] Fix | Delete
# defined for arguments greater than 0 (IronPython).
[393] Fix | Delete
try:
[394] Fix | Delete
result.__module__ = _sys._getframe(1).f_globals.get('__name__', '__main__')
[395] Fix | Delete
except (AttributeError, ValueError):
[396] Fix | Delete
pass
[397] Fix | Delete
[398] Fix | Delete
return result
[399] Fix | Delete
[400] Fix | Delete
[401] Fix | Delete
########################################################################
[402] Fix | Delete
### Counter
[403] Fix | Delete
########################################################################
[404] Fix | Delete
[405] Fix | Delete
class Counter(dict):
[406] Fix | Delete
'''Dict subclass for counting hashable items. Sometimes called a bag
[407] Fix | Delete
or multiset. Elements are stored as dictionary keys and their counts
[408] Fix | Delete
are stored as dictionary values.
[409] Fix | Delete
[410] Fix | Delete
>>> c = Counter('abcdeabcdabcaba') # count elements from a string
[411] Fix | Delete
[412] Fix | Delete
>>> c.most_common(3) # three most common elements
[413] Fix | Delete
[('a', 5), ('b', 4), ('c', 3)]
[414] Fix | Delete
>>> sorted(c) # list all unique elements
[415] Fix | Delete
['a', 'b', 'c', 'd', 'e']
[416] Fix | Delete
>>> ''.join(sorted(c.elements())) # list elements with repetitions
[417] Fix | Delete
'aaaaabbbbcccdde'
[418] Fix | Delete
>>> sum(c.values()) # total of all counts
[419] Fix | Delete
15
[420] Fix | Delete
[421] Fix | Delete
>>> c['a'] # count of letter 'a'
[422] Fix | Delete
5
[423] Fix | Delete
>>> for elem in 'shazam': # update counts from an iterable
[424] Fix | Delete
... c[elem] += 1 # by adding 1 to each element's count
[425] Fix | Delete
>>> c['a'] # now there are seven 'a'
[426] Fix | Delete
7
[427] Fix | Delete
>>> del c['b'] # remove all 'b'
[428] Fix | Delete
>>> c['b'] # now there are zero 'b'
[429] Fix | Delete
0
[430] Fix | Delete
[431] Fix | Delete
>>> d = Counter('simsalabim') # make another counter
[432] Fix | Delete
>>> c.update(d) # add in the second counter
[433] Fix | Delete
>>> c['a'] # now there are nine 'a'
[434] Fix | Delete
9
[435] Fix | Delete
[436] Fix | Delete
>>> c.clear() # empty the counter
[437] Fix | Delete
>>> c
[438] Fix | Delete
Counter()
[439] Fix | Delete
[440] Fix | Delete
Note: If a count is set to zero or reduced to zero, it will remain
[441] Fix | Delete
in the counter until the entry is deleted or the counter is cleared:
[442] Fix | Delete
[443] Fix | Delete
>>> c = Counter('aaabbc')
[444] Fix | Delete
>>> c['b'] -= 2 # reduce the count of 'b' by two
[445] Fix | Delete
>>> c.most_common() # 'b' is still in, but its count is zero
[446] Fix | Delete
[('a', 3), ('c', 1), ('b', 0)]
[447] Fix | Delete
[448] Fix | Delete
'''
[449] Fix | Delete
# References:
[450] Fix | Delete
# http://en.wikipedia.org/wiki/Multiset
[451] Fix | Delete
# http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html
[452] Fix | Delete
# http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm
[453] Fix | Delete
# http://code.activestate.com/recipes/259174/
[454] Fix | Delete
# Knuth, TAOCP Vol. II section 4.6.3
[455] Fix | Delete
[456] Fix | Delete
def __init__(*args, **kwds):
[457] Fix | Delete
'''Create a new, empty Counter object. And if given, count elements
[458] Fix | Delete
from an input iterable. Or, initialize the count from another mapping
[459] Fix | Delete
of elements to their counts.
[460] Fix | Delete
[461] Fix | Delete
>>> c = Counter() # a new, empty counter
[462] Fix | Delete
>>> c = Counter('gallahad') # a new counter from an iterable
[463] Fix | Delete
>>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping
[464] Fix | Delete
>>> c = Counter(a=4, b=2) # a new counter from keyword args
[465] Fix | Delete
[466] Fix | Delete
'''
[467] Fix | Delete
if not args:
[468] Fix | Delete
raise TypeError("descriptor '__init__' of 'Counter' object "
[469] Fix | Delete
"needs an argument")
[470] Fix | Delete
self = args[0]
[471] Fix | Delete
args = args[1:]
[472] Fix | Delete
if len(args) > 1:
[473] Fix | Delete
raise TypeError('expected at most 1 arguments, got %d' % len(args))
[474] Fix | Delete
super(Counter, self).__init__()
[475] Fix | Delete
self.update(*args, **kwds)
[476] Fix | Delete
[477] Fix | Delete
def __missing__(self, key):
[478] Fix | Delete
'The count of elements not in the Counter is zero.'
[479] Fix | Delete
# Needed so that self[missing_item] does not raise KeyError
[480] Fix | Delete
return 0
[481] Fix | Delete
[482] Fix | Delete
def most_common(self, n=None):
[483] Fix | Delete
'''List the n most common elements and their counts from the most
[484] Fix | Delete
common to the least. If n is None, then list all element counts.
[485] Fix | Delete
[486] Fix | Delete
>>> Counter('abcdeabcdabcaba').most_common(3)
[487] Fix | Delete
[('a', 5), ('b', 4), ('c', 3)]
[488] Fix | Delete
[489] Fix | Delete
'''
[490] Fix | Delete
# Emulate Bag.sortedByCount from Smalltalk
[491] Fix | Delete
if n is None:
[492] Fix | Delete
return sorted(self.iteritems(), key=_itemgetter(1), reverse=True)
[493] Fix | Delete
return _heapq.nlargest(n, self.iteritems(), key=_itemgetter(1))
[494] Fix | Delete
[495] Fix | Delete
def elements(self):
[496] Fix | Delete
'''Iterator over elements repeating each as many times as its count.
[497] Fix | Delete
[498] Fix | Delete
>>> c = Counter('ABCABC')
[499] Fix | Delete
12
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function