Edit File by line
/home/barbar84/www/wp-conte.../plugins/sujqvwi/AnonR/smanonr..../usr/lib64/python2....
File: collections.py
>>> sorted(c.elements())
[500] Fix | Delete
['A', 'A', 'B', 'B', 'C', 'C']
[501] Fix | Delete
[502] Fix | Delete
# Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1
[503] Fix | Delete
>>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
[504] Fix | Delete
>>> product = 1
[505] Fix | Delete
>>> for factor in prime_factors.elements(): # loop over factors
[506] Fix | Delete
... product *= factor # and multiply them
[507] Fix | Delete
>>> product
[508] Fix | Delete
1836
[509] Fix | Delete
[510] Fix | Delete
Note, if an element's count has been set to zero or is a negative
[511] Fix | Delete
number, elements() will ignore it.
[512] Fix | Delete
[513] Fix | Delete
'''
[514] Fix | Delete
# Emulate Bag.do from Smalltalk and Multiset.begin from C++.
[515] Fix | Delete
return _chain.from_iterable(_starmap(_repeat, self.iteritems()))
[516] Fix | Delete
[517] Fix | Delete
# Override dict methods where necessary
[518] Fix | Delete
[519] Fix | Delete
@classmethod
[520] Fix | Delete
def fromkeys(cls, iterable, v=None):
[521] Fix | Delete
# There is no equivalent method for counters because setting v=1
[522] Fix | Delete
# means that no element can have a count greater than one.
[523] Fix | Delete
raise NotImplementedError(
[524] Fix | Delete
'Counter.fromkeys() is undefined. Use Counter(iterable) instead.')
[525] Fix | Delete
[526] Fix | Delete
def update(*args, **kwds):
[527] Fix | Delete
'''Like dict.update() but add counts instead of replacing them.
[528] Fix | Delete
[529] Fix | Delete
Source can be an iterable, a dictionary, or another Counter instance.
[530] Fix | Delete
[531] Fix | Delete
>>> c = Counter('which')
[532] Fix | Delete
>>> c.update('witch') # add elements from another iterable
[533] Fix | Delete
>>> d = Counter('watch')
[534] Fix | Delete
>>> c.update(d) # add elements from another counter
[535] Fix | Delete
>>> c['h'] # four 'h' in which, witch, and watch
[536] Fix | Delete
4
[537] Fix | Delete
[538] Fix | Delete
'''
[539] Fix | Delete
# The regular dict.update() operation makes no sense here because the
[540] Fix | Delete
# replace behavior results in the some of original untouched counts
[541] Fix | Delete
# being mixed-in with all of the other counts for a mismash that
[542] Fix | Delete
# doesn't have a straight-forward interpretation in most counting
[543] Fix | Delete
# contexts. Instead, we implement straight-addition. Both the inputs
[544] Fix | Delete
# and outputs are allowed to contain zero and negative counts.
[545] Fix | Delete
[546] Fix | Delete
if not args:
[547] Fix | Delete
raise TypeError("descriptor 'update' of 'Counter' object "
[548] Fix | Delete
"needs an argument")
[549] Fix | Delete
self = args[0]
[550] Fix | Delete
args = args[1:]
[551] Fix | Delete
if len(args) > 1:
[552] Fix | Delete
raise TypeError('expected at most 1 arguments, got %d' % len(args))
[553] Fix | Delete
iterable = args[0] if args else None
[554] Fix | Delete
if iterable is not None:
[555] Fix | Delete
if isinstance(iterable, Mapping):
[556] Fix | Delete
if self:
[557] Fix | Delete
self_get = self.get
[558] Fix | Delete
for elem, count in iterable.iteritems():
[559] Fix | Delete
self[elem] = self_get(elem, 0) + count
[560] Fix | Delete
else:
[561] Fix | Delete
super(Counter, self).update(iterable) # fast path when counter is empty
[562] Fix | Delete
else:
[563] Fix | Delete
self_get = self.get
[564] Fix | Delete
for elem in iterable:
[565] Fix | Delete
self[elem] = self_get(elem, 0) + 1
[566] Fix | Delete
if kwds:
[567] Fix | Delete
self.update(kwds)
[568] Fix | Delete
[569] Fix | Delete
def subtract(*args, **kwds):
[570] Fix | Delete
'''Like dict.update() but subtracts counts instead of replacing them.
[571] Fix | Delete
Counts can be reduced below zero. Both the inputs and outputs are
[572] Fix | Delete
allowed to contain zero and negative counts.
[573] Fix | Delete
[574] Fix | Delete
Source can be an iterable, a dictionary, or another Counter instance.
[575] Fix | Delete
[576] Fix | Delete
>>> c = Counter('which')
[577] Fix | Delete
>>> c.subtract('witch') # subtract elements from another iterable
[578] Fix | Delete
>>> c.subtract(Counter('watch')) # subtract elements from another counter
[579] Fix | Delete
>>> c['h'] # 2 in which, minus 1 in witch, minus 1 in watch
[580] Fix | Delete
0
[581] Fix | Delete
>>> c['w'] # 1 in which, minus 1 in witch, minus 1 in watch
[582] Fix | Delete
-1
[583] Fix | Delete
[584] Fix | Delete
'''
[585] Fix | Delete
if not args:
[586] Fix | Delete
raise TypeError("descriptor 'subtract' of 'Counter' object "
[587] Fix | Delete
"needs an argument")
[588] Fix | Delete
self = args[0]
[589] Fix | Delete
args = args[1:]
[590] Fix | Delete
if len(args) > 1:
[591] Fix | Delete
raise TypeError('expected at most 1 arguments, got %d' % len(args))
[592] Fix | Delete
iterable = args[0] if args else None
[593] Fix | Delete
if iterable is not None:
[594] Fix | Delete
self_get = self.get
[595] Fix | Delete
if isinstance(iterable, Mapping):
[596] Fix | Delete
for elem, count in iterable.items():
[597] Fix | Delete
self[elem] = self_get(elem, 0) - count
[598] Fix | Delete
else:
[599] Fix | Delete
for elem in iterable:
[600] Fix | Delete
self[elem] = self_get(elem, 0) - 1
[601] Fix | Delete
if kwds:
[602] Fix | Delete
self.subtract(kwds)
[603] Fix | Delete
[604] Fix | Delete
def copy(self):
[605] Fix | Delete
'Return a shallow copy.'
[606] Fix | Delete
return self.__class__(self)
[607] Fix | Delete
[608] Fix | Delete
def __reduce__(self):
[609] Fix | Delete
return self.__class__, (dict(self),)
[610] Fix | Delete
[611] Fix | Delete
def __delitem__(self, elem):
[612] Fix | Delete
'Like dict.__delitem__() but does not raise KeyError for missing values.'
[613] Fix | Delete
if elem in self:
[614] Fix | Delete
super(Counter, self).__delitem__(elem)
[615] Fix | Delete
[616] Fix | Delete
def __repr__(self):
[617] Fix | Delete
if not self:
[618] Fix | Delete
return '%s()' % self.__class__.__name__
[619] Fix | Delete
items = ', '.join(map('%r: %r'.__mod__, self.most_common()))
[620] Fix | Delete
return '%s({%s})' % (self.__class__.__name__, items)
[621] Fix | Delete
[622] Fix | Delete
# Multiset-style mathematical operations discussed in:
[623] Fix | Delete
# Knuth TAOCP Volume II section 4.6.3 exercise 19
[624] Fix | Delete
# and at http://en.wikipedia.org/wiki/Multiset
[625] Fix | Delete
#
[626] Fix | Delete
# Outputs guaranteed to only include positive counts.
[627] Fix | Delete
#
[628] Fix | Delete
# To strip negative and zero counts, add-in an empty counter:
[629] Fix | Delete
# c += Counter()
[630] Fix | Delete
[631] Fix | Delete
def __add__(self, other):
[632] Fix | Delete
'''Add counts from two counters.
[633] Fix | Delete
[634] Fix | Delete
>>> Counter('abbb') + Counter('bcc')
[635] Fix | Delete
Counter({'b': 4, 'c': 2, 'a': 1})
[636] Fix | Delete
[637] Fix | Delete
'''
[638] Fix | Delete
if not isinstance(other, Counter):
[639] Fix | Delete
return NotImplemented
[640] Fix | Delete
result = Counter()
[641] Fix | Delete
for elem, count in self.items():
[642] Fix | Delete
newcount = count + other[elem]
[643] Fix | Delete
if newcount > 0:
[644] Fix | Delete
result[elem] = newcount
[645] Fix | Delete
for elem, count in other.items():
[646] Fix | Delete
if elem not in self and count > 0:
[647] Fix | Delete
result[elem] = count
[648] Fix | Delete
return result
[649] Fix | Delete
[650] Fix | Delete
def __sub__(self, other):
[651] Fix | Delete
''' Subtract count, but keep only results with positive counts.
[652] Fix | Delete
[653] Fix | Delete
>>> Counter('abbbc') - Counter('bccd')
[654] Fix | Delete
Counter({'b': 2, 'a': 1})
[655] Fix | Delete
[656] Fix | Delete
'''
[657] Fix | Delete
if not isinstance(other, Counter):
[658] Fix | Delete
return NotImplemented
[659] Fix | Delete
result = Counter()
[660] Fix | Delete
for elem, count in self.items():
[661] Fix | Delete
newcount = count - other[elem]
[662] Fix | Delete
if newcount > 0:
[663] Fix | Delete
result[elem] = newcount
[664] Fix | Delete
for elem, count in other.items():
[665] Fix | Delete
if elem not in self and count < 0:
[666] Fix | Delete
result[elem] = 0 - count
[667] Fix | Delete
return result
[668] Fix | Delete
[669] Fix | Delete
def __or__(self, other):
[670] Fix | Delete
'''Union is the maximum of value in either of the input counters.
[671] Fix | Delete
[672] Fix | Delete
>>> Counter('abbb') | Counter('bcc')
[673] Fix | Delete
Counter({'b': 3, 'c': 2, 'a': 1})
[674] Fix | Delete
[675] Fix | Delete
'''
[676] Fix | Delete
if not isinstance(other, Counter):
[677] Fix | Delete
return NotImplemented
[678] Fix | Delete
result = Counter()
[679] Fix | Delete
for elem, count in self.items():
[680] Fix | Delete
other_count = other[elem]
[681] Fix | Delete
newcount = other_count if count < other_count else count
[682] Fix | Delete
if newcount > 0:
[683] Fix | Delete
result[elem] = newcount
[684] Fix | Delete
for elem, count in other.items():
[685] Fix | Delete
if elem not in self and count > 0:
[686] Fix | Delete
result[elem] = count
[687] Fix | Delete
return result
[688] Fix | Delete
[689] Fix | Delete
def __and__(self, other):
[690] Fix | Delete
''' Intersection is the minimum of corresponding counts.
[691] Fix | Delete
[692] Fix | Delete
>>> Counter('abbb') & Counter('bcc')
[693] Fix | Delete
Counter({'b': 1})
[694] Fix | Delete
[695] Fix | Delete
'''
[696] Fix | Delete
if not isinstance(other, Counter):
[697] Fix | Delete
return NotImplemented
[698] Fix | Delete
result = Counter()
[699] Fix | Delete
for elem, count in self.items():
[700] Fix | Delete
other_count = other[elem]
[701] Fix | Delete
newcount = count if count < other_count else other_count
[702] Fix | Delete
if newcount > 0:
[703] Fix | Delete
result[elem] = newcount
[704] Fix | Delete
return result
[705] Fix | Delete
[706] Fix | Delete
[707] Fix | Delete
if __name__ == '__main__':
[708] Fix | Delete
# verify that instances can be pickled
[709] Fix | Delete
from cPickle import loads, dumps
[710] Fix | Delete
Point = namedtuple('Point', 'x, y', True)
[711] Fix | Delete
p = Point(x=10, y=20)
[712] Fix | Delete
assert p == loads(dumps(p))
[713] Fix | Delete
[714] Fix | Delete
# test and demonstrate ability to override methods
[715] Fix | Delete
class Point(namedtuple('Point', 'x y')):
[716] Fix | Delete
__slots__ = ()
[717] Fix | Delete
@property
[718] Fix | Delete
def hypot(self):
[719] Fix | Delete
return (self.x ** 2 + self.y ** 2) ** 0.5
[720] Fix | Delete
def __str__(self):
[721] Fix | Delete
return 'Point: x=%6.3f y=%6.3f hypot=%6.3f' % (self.x, self.y, self.hypot)
[722] Fix | Delete
[723] Fix | Delete
for p in Point(3, 4), Point(14, 5/7.):
[724] Fix | Delete
print p
[725] Fix | Delete
[726] Fix | Delete
class Point(namedtuple('Point', 'x y')):
[727] Fix | Delete
'Point class with optimized _make() and _replace() without error-checking'
[728] Fix | Delete
__slots__ = ()
[729] Fix | Delete
_make = classmethod(tuple.__new__)
[730] Fix | Delete
def _replace(self, _map=map, **kwds):
[731] Fix | Delete
return self._make(_map(kwds.get, ('x', 'y'), self))
[732] Fix | Delete
[733] Fix | Delete
print Point(11, 22)._replace(x=100)
[734] Fix | Delete
[735] Fix | Delete
Point3D = namedtuple('Point3D', Point._fields + ('z',))
[736] Fix | Delete
print Point3D.__doc__
[737] Fix | Delete
[738] Fix | Delete
import doctest
[739] Fix | Delete
TestResults = namedtuple('TestResults', 'failed attempted')
[740] Fix | Delete
print TestResults(*doctest.testmod())
[741] Fix | Delete
[742] Fix | Delete
12
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function