Practice question · Multiple choice
A word-frequency counter needs to split text, normalise case, count occurrences and report the top results. Why is choosing a dictionary for the counting step the decision that shapes the whole program?
Hints
- For each word in the text, what operation does the counter perform?
- Ask what that operation costs in a dictionary and in a list of pairs.
Show the answer
C. Because every word needs a lookup, and a dictionary makes that O(1).
Why
The counting step performs one lookup per word, so its cost is multiplied by the length of the text. O(n) with a dictionary and O(n²) with a list of pairs, fine on a paragraph and hopeless on a book. Splitting and normalising have no such leverage. Dictionaries are not sorted either, so reporting still needs a sort, cheap, because it runs once rather than n times.
Practise Integrated Programming Synthesis
The app has 5 more questions on this lesson, and keeps your place in the course. Computer Science I is free to start.
More questions on Integrated Programming Synthesis
- Order the tasks of building the word-frequency counter so that each one can be tested as soon as it is…
- A word-frequency program is asked to handle a 50 GB file that will not fit in memory. Which part of the…
- Sort each part of the word-frequency program by whether it can be written as a pure function or must carry…
- Select every edge case the lesson says the word-frequency counter's tests should cover.