Overview
Find the most frequent word in a text with one pass and a dict of counts, and avoid str.count(), which rescans the text and counts the inside of other words.
- counts[key] = counts.get(key, 0) + 1
- ties broken by first appearance
- str.count() rescans and matches substrings
Short Course
A dict of counts answers "how many of each?" in one pass: one +1 per item.
Trap: text.count(word) rescans the whole text for every word, and it also
counts "the" inside "there".
counts = {}
for status in ["200", "404", "200"]:
counts[status] = counts.get(status, 0) + 1
counts # {'200': 2, '404': 1}
Task
Write top_word(text): the most frequent word (split on spaces), counted
ignoring case and returned in lowercase. On a tie, return the word that appears first. Example:
top_word('the cat and the hat') → 'the'.
Test Suites
Pending
Next
Output