A Counter is a container that keeps track of how many times equivalent values are added. It can be used to implement the same algorithms for which other languages commonly use bag or multiset data structures.

Initilizing


In [1]:
import collections
print(collections.Counter(['a', 'b', 'c', 'd', 'a', 'c']))


Counter({'a': 2, 'c': 2, 'b': 1, 'd': 1})

In [2]:
c = collections.Counter()
print('initilize ', c)
c.update('abcdaab')
print('sequece', c)
c.update({'a':1, 'd':5})
print('Dict :',c)


initilize  Counter()
sequece Counter({'a': 3, 'b': 2, 'c': 1, 'd': 1})
Dict : Counter({'d': 6, 'a': 4, 'b': 2, 'c': 1})

Accessing Counts


In [4]:
c = collections.Counter('abcdaab')
for letter in 'abdce':
    print('{}:{}'.format(letter, c[letter]))


a:3
b:2
d:1
c:1
e:0

In [6]:
c = collections.Counter('extremely')
c['z'] = 0
print(c)
print(list(c.elements()))


Counter({'e': 3, 'x': 1, 't': 1, 'r': 1, 'm': 1, 'l': 1, 'y': 1, 'z': 0})
['e', 'e', 'e', 'x', 't', 'r', 'm', 'l', 'y']

Arithmetic


In [7]:
import collections
c1 = collections.Counter(['a','b', 'c', 'a', 'b', 'b'])
c2 = collections.Counter('alphabet')
print('C1:', c1)
print('C2:', c2)
print('\n Combined counts')
print(c1+c2)
print('\n subtractions')
print(c1-c2)
print('\n Interaction')
print(c1 & c2)
print('\n union')
print(c1 | c2)


C1: Counter({'b': 3, 'a': 2, 'c': 1})
C2: Counter({'a': 2, 'l': 1, 'p': 1, 'h': 1, 'b': 1, 'e': 1, 't': 1})

 Combined counts
Counter({'a': 4, 'b': 4, 'c': 1, 'l': 1, 'p': 1, 'h': 1, 'e': 1, 't': 1})

 subtractions
Counter({'b': 2, 'c': 1})

 Interaction
Counter({'a': 2, 'b': 1})

 union
Counter({'b': 3, 'a': 2, 'c': 1, 'l': 1, 'p': 1, 'h': 1, 'e': 1, 't': 1})