The Word Count problem

I really love this problem because there are so many things to explore and learn about Python here. In this, and the next few articles, we will explore some of the dimensions of this problem.

In the previous post, I wrote about the elegance with which you can drop the last item from a list–or character from a string–using negative indexing and negative slices. This particular snippet of code comes from the word count problem, a starter lab that I use when doing my python trainings.

Here is the problem statement

Given a string of words, count how many times each word appears in the string.

For example: "the quick dog and the quick fox ran the quick race and the fox ran quick" should give the output {"the": 4, "quick": 4, "dog": 1, "and": 2, "fox": 2, "ran": 2, "race": 1}

Assume that the whole string is in lowercase and there is no punctuation anywhere in the string. We will look into handling case and punctuation later.

If you are new to Python, then you might want to stop here and try out the problem yourself. Otherwise, it should not be too difficult. You want to loop through the words and keep track of the count in a dictionary–if the word is already present in the dictionary then increment its count, otherwise add it to the dictionary with a count of one.

In the next few articles, we will take a look at different features of Python that we can use to solve this problem.


Sign in or become a Playful Python member to join the conversation.
Just enter your email below to get a log in link.