The three most common words

Find the most common words in a line.

What to build

A program that counts and then ranks.

Requirements

  • Read a line of words.
  • Print up to three words, most frequent first, each as WORD COUNT.
  • Words with equal counts are ordered by which appeared first.

Input

One line of lowercase words separated by spaces.

Output

Up to three lines.

Constraints

There are from 1 to 1000 words.

Example

Input:

a b a c b a d

Output:

a 3
b 2
c 1

Why it works

Python's sort is stable, meaning equal items keep their order. So sorting the dictionary's items by count alone handles the rule for ties with no extra code.

Examples

Example 1 · Input
a b a c b a d
Expected output
a 3
b 2
c 1
Example 2 · Input
hello
Expected output
hello 1

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Count the words first, as in the lesson.

Hint 2

sorted can sort by a key. Use the negative count, so that the largest comes first.

Hint 3

Sorting keeps equal items in their original order, and a dictionary keeps first-seen order.

Solution

Show one correct solution (try it yourself first)
words = input().split()
counts = {}
for word in words:
    counts[word] = counts.get(word, 0) + 1
ranked = sorted(counts.items(), key=lambda pair: -pair[1])
for word, count in ranked[:3]:
    print(word, count)

Lesson: Dictionaries →