The Word Counter
An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- easy
- Seniority
- L3
- Asked in
- phData
Problem
Each whitespace-separated token in text is a word, possibly with any of the characters .,!?;:'"()- stuck to either end; those edge characters are not part of the word, but every other symbol is. Return how many times each word appears, skipping any token made up only of those edge characters.
How many times does each word show up in a file?
Example 1
Input:
text = "Hello world hello World"
Output:
{"hello":2,"world":2}Example 2
Input:
text = "Ship it! Ship it... (now)"
Output:
{"ship":2,"it":2,"now":1}Worked solution and explanation
Why this problem exists in real interviews
This tests text processing fundamentals: splitting, case normalization, punctuation stripping, and frequency counting. It is a complete mini-pipeline that mirrors real NLP preprocessing.
Break down the requirements
Step 1: Split the text on whitespace
Use .split() to handle multiple spaces and newlines.
Step 2: Normalize each word: lowercase and strip punctuation
Convert to lowercase and remove non-alphanumeric characters from the edges of each word.
Step 3: Count occurrences in a dict
Skip empty strings that result from stripping and accumulate counts.
The solution
def count_word_frequency(text: str) -> dict:
words = text.lower().split()
freq = {}
for raw_word in words:
word = raw_word.strip(".,!?;:'\"()-")
if word:
freq[word] = freq.get(word, 0) + 1
return freqCommon follow-up questions
- How would you handle contractions like "don't"? (Tests whether the apostrophe should be stripped or kept.)
- What if you needed to count bigrams instead of unigrams? (Tests sliding a window of size 2 over the word list.)
- How would you process this in a MapReduce framework? (Tests the classic word count MapReduce pattern: map emits (word, 1), reduce sums.)