Exercise: Word count

Time to put dicts, Counter and sorting together.

Exercise: finish top_words(text, n). It returns the n most common words in text as (word, count) pairs.

  • Split on whitespace with text.split(). Don't worry about punctuation.
  • Count words without caring about case, and return them lowercased: "Go" and "go" are the same word.
  • Higher counts come first. Words with the same count are sorted alphabetically.
  • If there are fewer than n distinct words, return all of them.

Careful: Counter.most_common breaks ties by the order words first appeared, not alphabetically. You need your own sort with a tuple key. Look back at the Sorting page.

Press Check to run the tests.