MCPcopy Create free account
hub / github.com/ActiveState/code / Counter

Class Counter

recipes/Python/577664_Counter_class/recipe-577664.py:5–184  ·  view source on GitHub ↗

Dict subclass for counting hashable objects. Sometimes called a bag or multiset. Elements are stored as dictionary keys and their counts are stored as dictionary values. >>> Counter('zyzygy') Counter({'y': 3, 'z': 2, 'g': 1})

Source from the content-addressed store, hash-verified

3from itertools import repeat, ifilter
4
5class Counter(dict):
6 '''Dict subclass for counting hashable objects. Sometimes called a bag
7 or multiset. Elements are stored as dictionary keys and their counts
8 are stored as dictionary values.
9
10 >>> Counter('zyzygy')
11 Counter({'y': 3, 'z': 2, 'g': 1})
12
13 '''
14
15 def __init__(self, iterable=None, **kwds):
16 '''Create a new, empty Counter object. And if given, count elements
17 from an input iterable. Or, initialize the count from another mapping
18 of elements to their counts.
19
20 >>> c = Counter() # a new, empty counter
21 >>> c = Counter('gallahad') # a new counter from an iterable
22 >>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping
23 >>> c = Counter(a=4, b=2) # a new counter from keyword args
24
25 '''
26 self.update(iterable, **kwds)
27
28 def __missing__(self, key):
29 return 0
30
31 def most_common(self, n=None):
32 '''List the n most common elements and their counts from the most
33 common to the least. If n is None, then list all element counts.
34
35 >>> Counter('abracadabra').most_common(3)
36 [('a', 5), ('r', 2), ('b', 2)]
37
38 '''
39 if n is None:
40 return sorted(self.iteritems(), key=itemgetter(1), reverse=True)
41 return nlargest(n, self.iteritems(), key=itemgetter(1))
42
43 def elements(self):
44 '''Iterator over elements repeating each as many times as its count.
45
46 >>> c = Counter('ABCABC')
47 >>> sorted(c.elements())
48 ['A', 'A', 'B', 'B', 'C', 'C']
49
50 If an element's count has been set to zero or is a negative number,
51 elements() will ignore it.
52
53 '''
54 for elem, count in self.iteritems():
55 for _ in repeat(None, count):
56 yield elem
57
58 # Override dict methods where the meaning changes for Counter objects.
59
60 @classmethod
61 def fromkeys(cls, iterable, v=None):
62 raise NotImplementedError(

Callers 9

copyMethod · 0.70
__add__Method · 0.70
__sub__Method · 0.70
__or__Method · 0.70
__and__Method · 0.70
__init__Method · 0.50
recipe-577535.pyFile · 0.50
__init__Method · 0.50
make_graphFunction · 0.50

Calls

no outgoing calls

Tested by

no test coverage detected