Counting with a Dictionary

The counting pattern

“How many times does each thing appear?” is one of the most common questions in programming. A dictionary answers it in one pass:

votes = ["tea", "coffee", "tea", "juice", "tea", "coffee"]
count = {}
for v in votes:
    count[v] = count.get(v, 0) + 1
print(count)

Output

{'tea': 3, 'coffee': 2, 'juice': 1}

count.get(v, 0) gives the current count, or 0 if we haven't seen v yet.

Counter does it for you

from collections import Counter

c = Counter("mississippi")
print(c)
print(c["s"])
print(c.most_common(2))

Output

Counter({'i': 4, 's': 4, 'p': 2, 'm': 1})
4
[('i', 4), ('s', 4)]

Anagrams

Two words are anagrams if they use exactly the same letters, like listen and silent. Same letter counts → anagram:

from collections import Counter

def is_anagram(a, b):
    return Counter(a) == Counter(b)

print(is_anagram("listen", "silent"))
print(is_anagram("apple", "paper"))

Output

True
False

Tip: Sorting both words also works (sorted(a) == sorted(b)), but that's O(n log n). Counting is O(n).

HOME LABS COMMUNITY DASHBOARD