Practice

Problem 4 of 10

Problem · Medium · 25 min

The most common words

  • Medium
  • Hash maps
  • Sorting
  • Strings

Write top_words(text, count). It returns a list of the count words that appear most often in the text. Each item of the list is a list [word, times].

  • A word is a run of letters (a to z). Any other character ends a word. The case of a letter does not matter: write each word in lower case.
  • Put the words that appear more often first. If two words appear the same number of times, put the word that comes first in the alphabet first.
  • If the text has fewer than count different words, return all of them.
  • If count is 0, or if the text has no words, return an empty list.

Examples

Call Result
top_words('the cat and the hat and the bat', 2) [['the', 3], ['and', 2]]
top_words('b a b a c', 3) [['a', 2], ['b', 2], ['c', 1]]
top_words('', 5) []

Tasks

2 to do

  1. Task 1, not checked yet. Make top_words pass the example tests.

  2. Task 2, not checked yet. Make top_words pass the hidden tests.

Task 1 of 2

Make top_words pass the example tests.

All tasks

main.py

Ctrl+Enter runs your code. Ctrl+Shift+Enter runs all the tests. Press Esc, then Tab, to leave the editor.

Output

Press Run to see your result

Your output shows here. Press Run to try your code.