211. Python Program to Count How Often Each Word Appears
MediumPhase 2 · Practice
This one takes a few steps. It uses split(), a dictionary and sorted(), and you know all three.
Overview
Counting words is a common interview question, and a dictionary is the right tool for it. Search engines and word clouds start with the same count.
Problem Statement
Hana writes a short poem and wants to see how often each word appears.
- Capital letters do not matter:
Go,goandGOare the same word. Print every word in small letters. - Print one line for each different word:
<word>: <count>. - Print the words in A to Z order.
Examples
Example 1. Input the cat and the hat gives:
and: 1
cat: 1
hat: 1
the: 2
Why: the appears twice, and the other words appear once. From A to Z, and comes first and the comes last.
Example 2. Input Go go GO stop gives:
go: 3
stop: 1
Why: in small letters, all three forms are go, so go appears 3 times.
Input
One line of words, with one space between them (1 word or more). The words have letters only. Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.
Output
One line for each different word, <word>: <count>, in A to Z order. The tests try 7 different inputs, also one word and words with capital letters.
Try it first. The solution opens when you solve this question, or after 3 tries with Submit.