Final: Top k Words
Completed
Read a paragraph and k. Print the k most frequent words (ignore capital letters) with their counts, most frequent first; ties are broken alphabetically. Words are separated by spaces and contain only letters.
Input
Line 1: the text. Line 2: k.
Output
k lines: <word> <count>.
Example
Input
the day is sunny the the the sunny is is 4
Output
the 4 is 3 sunny 2 day 1
Editor
Python
Hints
Count with a dict or Counter.
Sort by (-count, word) and take the first k.
Solution explanation
Hashing to count, then sorting with a tuple key: O(n + u log u) for u different words.
Show solution
from collections import Counter
words = input().lower().split()
k = int(input())
c = Counter(words)
for w, n in sorted(c.items(), key=lambda t: (-t[1], t[0]))[:k]:
print(w, n) Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module