Which fix removes the bug?
counts = {}
for word in words:
counts[word] += 1
- Use
counts.get(word, 0) - Sort the words first
- Convert words to a set
- Initialise counts to zero
The first sighting of a word has no key yet, so
Play Problem Solving ▸
+= 1 raises KeyError.