🎓 A1Learner
🔍
0 of 47 lessons completed

Counting with a Hash Map

Counting with a hash map is storing each distinct value with its count in a table. The table gives the count for any value in one lookup.

The recognition signal

The signal is a question about how often values appear.

signals = ["Question asks how often values appear", "One value may appear many times", "The answer needs a count for each value"]
for signal in signals:
    print("Signal " + signal)

The template

Counter builds the count table in one pass.

from collections import Counter
print(Counter(["a", "b", "a", "c", "b", "a"]))

Worked problem most common value

The most common value is the key with the largest count.

from collections import Counter
counts = Counter(["red", "blue", "red", "green", "red", "blue"])
most = max(counts, key=counts.get)
print(counts)
print("Most common " + most)
print("Count " + str(counts[most]))

Example

from collections import Counter
print(Counter("listen") == Counter("silent"))
print(Counter("hello") == Counter("world"))

Key points

  • A hash map stores a value as a key and its count as a number.
  • Use a hash map to count values in a list.
  • Use Counter from collections to count values quickly.
  • A lookup in a hash map returns the stored count.
  • A missing key means the value has not been seen yet.
  • Counting with a hash map is simply tallying each value once.

The program builds a count table for each word. It compares the two tables for matching counts. Equal tables mean the words use the same letters.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What does Counter build from a list?