Sunday, June 3, 2012

Tour golang Exercise: Maps #45 WordCount Solution

This exercise from the golang tour asks for a function that will count the number of times each word appears in a string. I think of it as using a hash to contain a histogram of word frequency. The if/else could be tighter if go had a ternary operator.


package main

import "strings"
import "fmt"

func WordCount (s string) map[string]int {

    substrs := strings.Fields(s)

    // key,value  ==> word,count
    // iterate over substrs, if key in map, value++, else create

    counts := make(map[string]int)

    for _, word := range substrs {
        _, ok := counts[word]

        if ok == true {
          counts[word] += 1
        } else {
          counts[word] = 1

    return counts

func main() {
  fmt.Println(WordCount("now is the now is the go go go it a a a a a"))
  fmt.Println(WordCount("1 2 3 11 22 33 1 2 3"))


[now is the now is the go go go it a a a a a]
map[now:2 the:2 go:3 a:5 is:2 it:1]
[1 2 3 11 22 33 1 2 3]
map[2:2 33:1 1:2 11:1 22:1 3:2]

Common Error:

./wordcount2.go:20: cannot convert true to type int
./wordcount2.go:20: invalid operation: ok == true (mismatched types int and bool)

This occurs when attempting: 

    ok := counts[word]

Instead of:
    _, ok := counts[word]


  1. Hey Kevin

    I had the same solution you did, but noticed you don't need the conditional since you already defined you map to have element types of int. You can simply update your map as so

    counts[word] += 1

    Also, if you were to use the if statement, you can use the shorthand !ok since you are testing a boolean value.

    I made a gist for my solution here:

    Kindest regards

    Thomas Frederiksen

  2. This comment has been removed by a blog administrator.

  3. Meanwhile several tour operators wishing to change the habits of lots of tourists offer very attractive prices just in good time long before the beginning of the here

  4. I have bookmarked your blog, the articles are way better than other similar blogs.. thanks for a great blog! seo expert

  5. From the beginning days of your new physical fitness program, the aim of that activity will be to achieve the lower end of the target heart rate range and keep the heart rate within that range for the duration of the exercise. api fat burner advanced review