Counter
from collections import Counter
Count Str Characters
my_counter = Counter("Leetcode 4 life!")
Elements
sorted(my_counter.elements())
[' ', ' ', '!', '4', 'L', 'c', 'd', 'e', 'e', 'e', 'e', 'f', 'i', 'l', 'o', 't']
Most Common
Counter('abracadabra').most_common(3)
[('a', 5), ('b', 2), ('r', 2)]
Common Patterns
sum(c.values()) # total of all counts
c.clear() # reset all counts
list(c) # list unique elements
set(c) # convert to a set
dict(c) # convert to a regular dictionary
c.items() # convert to a list of (elem, cnt) pairs
Counter(dict(list_of_pairs)) # convert from a list of (elem, cnt) pairs
c.most_common()[:-n-1:-1] # n least common elements
+c # remove zero and negative counts
Math Patterns
c = Counter(a=3, b=1)
d = Counter(a=1, b=2)
c + d # add two counters together: c[x] + d[x]
Counter({'a': 4, 'b': 3})
c - d # subtract (keeping only positive counts)
Counter({'a': 2})
c & d # intersection: min(c[x], d[x])
Counter({'a': 1, 'b': 1})
c | d # union: max(c[x], d[x])
Counter({'a': 3, 'b': 2})
Unary
c = Counter(a=2, b=-4)
+c
Counter({'a': 2})
-c
Counter({'b': 4})