Python Python Collections (2016, retired 2019) Dictionaries Word Count

Why is my solution not working? It returns correct answer in my terminal.

def word_count(string): ... word_list = string.split(" ") ... freq = {} ... lower_case = lower(word_list) ... for word in lower_case: ... if (word in freq): ... freq[word.lower()] +=1 ... else: ... freq[word.lower()] = 1 ... return freq

def lower(lst): ... new = [] ... for item in lst: ... item = item.lower() ... new.append(item) ... return new ...

wordcount.py
# E.g. word_count("I do not like it Sam I Am") gets back a dictionary like:
# {'i': 2, 'do': 1, 'it': 1, 'sam': 1, 'like': 1, 'not': 1, 'am': 1}
# Lowercase the string to make it easier.

def lower(lst):
    new = []
    for item in lst:
        new.append(item.lower())
    return new

def word_count(string):
        word_list = string.split(" ")
        freq = {}
        lower_case = lower(word_list)
        for word in lower_case:
            if (word in freq):
                freq[word.lower()] += 1
            else:
                freq[word.lower()] = 1
        return freq

1 Answer

Steven Parker
Steven Parker
203,700 Points

I'm surprised that this worked outside of the challenge, as I'm not familiar with a "lower" function that would convert an entire list into lower case and return it as another list. But you can simply convert the string before you split it.

Also, the challenge wants you to split words on "all whitespace", so the argument to "split" should be left empty or set to None:

        lower_case = string.lower().split()

And since you converted the string already, you won't need to convert the individual words:

                freq[word] += 1

Thanks!! I don't know why several other solutions I tried worked in my terminal and not in the treehouse workspace, but I used your lower_case function and it passed :)