Count Word Frequencies
Checking your account…
Sign in to save your code and progress across devices. The lesson and problem statement remain public.
Loading the interactive Practice workspace.If it does not appear, the problem and learning material remain readable, but browser execution is unavailable.Reload Practice workspace
Problem
Implement word_frequencies(words). Return a dictionary mapping every token to its occurrence count.
Starter code
def word_frequencies(words):
passTest cases
sample
{
"args": [
[
"red",
"blue",
"red"
]
]
}Expected: {"red":2,"blue":1}
Wizard outline
- Step 1: Advance one frequency count
Initialize a missing word at one and increment an existing word. Every frequency map is built from the same local dictionary transition.
- Step 2: Fold the transition over all words
Return the complete token-to-count mapping. Starting from an empty dictionary and applying the verified transition once per word preserves every occurrence.
Footguns and prerequisites
- A dictionary comprehension records presence but loses repeated occurrences.
- dictionaries and sets
Reviewed references
Prepared Interview Problems
- Group Words by Anagram Signature(opens in a new tab)
Counting tokens into a hash map rehearses the same frequency-signature construction used to place anagrams into canonical groups.
Recommended approach and implementation
Increment a dictionary entry for each token.
Why it works: Each loop adds one for exactly the current occurrence, so final values equal occurrence counts.
def _increment(counts, word):
counts[word] = counts.get(word, 0) + 1
return counts
def word_frequencies(words):
counts = {}
for word in words:
_increment(counts, word)
return counts