Problem overview
The method wordFrequency receives a string, sentence, made of lowercase words separated by single spaces, and returns a dictionary. Each word of the sentence is a key, and its value is the number of times the word appears. The order of the entries doesn't matter.
For "the cat and the hat" the result is {'the': 2, 'cat': 1, 'and': 1, 'hat': 1}. For "go go go" it is {'go': 3}: the same word three times is one key with the value 3. A one-word sentence such as "hello" gives {'hello': 1}.
Approach: split, then count
The problem has two parts. First, turn the sentence, which is one string, into a list of words. Then count the items of that list with a dictionary, the same pattern that counts letters in a string.
The first part is done by the string method split(). Called with no argument, it cuts the string at whitespace and returns a list of the pieces. The second part is the counting loop: a word that is already a key gets its count raised, and a new word starts at 1.
Step by step
- Split the sentence.
words = sentence.split()gives['the', 'cat', 'and', 'the', 'hat']for the first example. - Create an empty dictionary named
counts. No word has been counted yet. - Loop over
wordswithfor word in words. Every word adds 1 to its own count, so each gets a turn. - Raise the count of a known word. If
word in counts, runcounts[word] += 1. - Start a new word at 1 in an
else:counts[word] = 1. Adding 1 to a key that doesn't exist yet would raise aKeyError. - Return
countsafter the loop.
The solution in Python
class Solution:
def wordFrequency(self, sentence: str) -> Dict[str, int]:
words = sentence.split()
counts = {}
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
return counts
Python details to keep in mind:
split()without an argument treats any run of whitespace as one separator and ignores leading and trailing whitespace. For"the cat and", with two spaces between "cat" and "and", the result is{'the': 1, 'cat': 1, 'and': 1}, with no empty-string key.split(" ")would behave differently there: it returns an empty string for every extra space.- Keys are compared exactly. The words are all lowercase here. In general,
"The"and"the"are different keys, so text with mixed case needslower()first. - Strings can be keys. Strings are immutable, so Python allows them as dictionary keys, as it does for numbers and tuples. Lists can't be keys.
- The same pattern counts anything. Only the source of the items changes: letters of a string, words of a sentence, numbers of a list.
Edge cases and common mistakes
- Counting the sentence instead of the words. Looping over
sentencedirectly visits single characters, so the keys would be letters and spaces. Thesplit()call comes first. - Forgetting the first-time case. Without the
elsebranch, the first word raisesKeyError. - Treating the loop variable as the count. The loop variable
wordis the word. Its count lives incounts[word]. - One word.
"hello"splits into a one-item list, and the result is{'hello': 1}.
Testing
"the cat and the hat"gives{'the': 2, 'cat': 1, 'and': 1, 'hat': 1}."go go go"gives{'go': 3}."hello"gives{'hello': 1}.
