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.
Did you like this article?
If you liked this article, consider subscribing to this site. Subscribing is free.
Why subscribe? Here are three reasons:
- You will get every new article as an email in your inbox, so you never miss an article
- You will be able to comment on all the posts, ask questions, etc
- Once in a while, I will be posting conference talk slides, longer form articles (such as this one), and other content as subscriber-only