Problem overview
The function wordFrequency takes a string, sentence, and returns a map[string]int: each word of the sentence is a key and its value is how many times the word appears. The words are lowercase and separated by single spaces, and there is at least one word. The order of entries doesn't matter.
For "the cat and the hat" the result is map[and:1 cat:1 hat:1 the:2]: "the" appears twice and every other word once.
Approach: split, then count
The problem has two parts. First, turn the sentence into a slice of words. Then count the words with a map, the same way you would count letters: a known word gets +1, a new word starts at 1.
Step by step
- Split the sentence.
strings.Split(sentence, " ")cuts the string at every space and returns a[]string. Because the words are separated by single spaces, the pieces are exactly the words. - Create the map.
map[string]int{}starts empty, since nothing has been counted. - Loop over the words with
for _, word := range words. - Known word.
if _, ok := counts[word]; okis true when the word is already a key. Then add 1 to its count. - New word. In the
elsebranch, setcounts[word]to 1. - Return
countsafter the loop.
Tracing the example
Reading "the cat and the hat" one word at a time, the map changes like this:
| word read | counts afterwards |
|---|---|
| the | map[the:1] |
| cat | map[cat:1 the:1] |
| and | map[and:1 cat:1 the:1] |
| the | map[and:1 cat:1 the:2] |
| hat | map[and:1 cat:1 hat:1 the:2] |
The second "the" finds its key already present, so the count rises from 1 to 2 instead of a new key appearing. The table prints each map sorted by key, which is how fmt.Println shows maps.
The solution in Go
func wordFrequency(sentence string) map[string]int {
words := strings.Split(sentence, " ")
counts := map[string]int{}
for _, word := range words {
if _, ok := counts[word]; ok {
counts[word] += 1
} else {
counts[word] = 1
}
}
return counts
}
Go details worth knowing
- The
stringspackage.strings.Splitlives in the standard library'sstringspackage. The lesson's editor already has it available. In a program of your own, putimport "strings"at the top of the file. - Single spaces only.
strings.Splitwith" "makes an empty string for every extra space: splitting"a b"(two spaces) gives three pieces, with an empty one in the middle. This lesson promises single spaces, so that doesn't happen here. For messier text,strings.Fieldssplits on any run of white space and drops the empty pieces. - The two-value lookup.
v, ok := m[k]gives the value and whether the key exists. Declaring it in theifheader limitsokto theifand itselse. - Shorter form.
counts[word]++does the same job in one line, since a missing key reads as 0. The explicit branches show what is happening. - Order.
fmt.Printlnprints a map sorted by key, but arangeover the map visits entries in random order.
Edge cases and common mistakes
- A repeated word gives one key.
"go go go"returnsmap[go:3]. - One word.
"hello"returnsmap[hello:1]. - Splitting on the wrong separator. Splitting on
""cuts the string into characters, not words, so the counts would be for letters. - Writing to a nil map.
var counts map[string]intfollowed bycounts[word] = 1panics with "assignment to entry in nil map". Create the map with a literal ormake.
Testing
"the cat and the hat"givesmap[and:1 cat:1 hat:1 the:2]."go go go"givesmap[go:3]."hello"givesmap[hello:1].
