Word Frequency
Medium · 50 XPPrint the three most common words in the starter text, one per line as word count.
the 4 and 3 fox 2
Counter(text.split()).most_common(3)
from collections import Counter
text = "the quick fox and the lazy dog and the sleepy cat and the fox"
for word, count in Counter(text.split()).most_common(3):
print(word, count)
Run your code to check it…
How to approach Word Frequency
Frequency counting is a dictionary that maps each word to how many times it has been seen. You can build one by hand with counts[w] = counts.get(w, 0) + 1, but collections.Counter exists precisely for this and does it in one call.
Counter(text.split()).most_common(3) returns the three highest counts as (word, count) pairs, largest first. Unpack each pair in the loop and print them with a space between, which is what print(word, count) does by default.
Worked through on this data
- Splitting on whitespace gives 14 words. "the" appears 4 times and "and" 3 times.
- "fox" appears twice. Every other word (quick, lazy, dog, sleepy, cat) appears once.
- The top three are the 4, and 3, fox 2: one pair per line, matching the target.
Common mistakes
- Real text has capitals and punctuation, so "The" and "fox." would count as different words. Normalise with
.lower()and strip punctuation before counting. - Sorting a dict by value by hand and forgetting
reverse=Truegives the three least common words. text.split(" ")treats two spaces in a row as an empty word; plaintext.split()does not.
Time and space
Counting is one pass, O(n) in the number of words. most_common(k) uses a heap, so it costs O(m log k) over m distinct words rather than a full sort.
Where this shows up
Word counts are the start of search indexing, log analysis (which error message is most common?) and every "top 10" report a product team asks for.
Take it further
Read a paragraph of real text, lowercase it, strip punctuation with str.maketrans, and ignore a small set of stop words such as "the" and "and" before counting.