3. Top K Frequent Words
Difficulty: Easy · Topic: Core Python & data structures
Write top_words(text, k): the k most frequent words of text as a list of (word, count) tuples, most frequent first.
- Words are separated by whitespace. Compare them in lower case, and strip these characters from both ends of a word:
. , ! ? ; : " ' ( ). A word that is empty after stripping is ignored. - Ties (the same count) are ordered alphabetically.
- Return fewer than
ktuples when there are fewer distinct words.
Your code runs in CPython on our servers against 6 tests, including hidden ones.
Sample test
top_words("the cat and the hat and the bat", 2)Expected: [('the', 3), ('and', 2)]
Hints
Hint 1
collections.Counter(words) counts everything in one pass.Hint 2
Counter.most_common(k) breaks ties by first appearance, not alphabetically, so sort yourself.Hint 3
Sort by a tuple key:key=lambda kv: (-kv[1], kv[0]) puts higher counts first, then words A to Z.Learn the concepts
- Counter, defaultdict and deque · 6 min read. Count, group and keep the last N with the collections module, and the traps in each.
More Python problems
- Flatten a Nested List · Easy
- Squares of the Even Numbers · Easy
- Invert a Dictionary · Easy
- Merge Dicts and Sum Shared Keys · Easy
- Group Records by Key · Easy
- Count Words in Reviews · Easy
- Zip Columns into Records · Easy
- Find the Missing IDs · Easy
- Safe Min and Max · Easy
- Sort by Several Keys · Medium
- Fix the Mutable Default Argument · Medium
- Override a Config Without Changing It · Medium
- Keep the Last N Events · Medium