Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

Nicolas Baranowski
Nicolas Baranowski
4,813 Points

word_count bug?

for the word count challenge (https://teamtreehouse.com/library/python-collections-2/dictionaries/word-count) can anyone find why my code is not accepted?

Seems like the console is giving me the right results..

Thanks

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 word_count(phrase):

    dic = {}
    phraseL = ""
    word_list_clean = []

    for char in phrase:
        charL = char.lower()
        phraseL += charL

    #print(phraseL)

    word_list = phraseL.split(" ")

    #print(word_list)

    for word in word_list:
        if word != "":
            word_list_clean.append(word)
        else:
            continue

    #print(word_list_clean)

    for word in word_list_clean:
        if word not in dic:
            dic[word] = 1
        else:
            dic[word] += 1

    #print(dic)

    return dic

2 Answers

Steven Parker
Steven Parker
231,269 Points

The error message gives you a hint: "Bummer! Hmm, didn't get the expected output. Be sure you're lowercasing the string and splitting on all whitespace!".

To split on "all whitespace" the argument of "split" should be left empty. Specifying a space causes it to split only on individual spaces.

Nicolas Baranowski
Nicolas Baranowski
4,813 Points

Thank you Steven.

I will try this. However I thought that this function:

for word in word_list: if word != "": word_list_clean.append(word) else: continue

would allow to compensate for this by cleaning word_list into a word_list_clean

Steven Parker
Steven Parker
231,269 Points

That would only remove empty strings from the list, it still wouldn't split on "white space" characters other than literal spaces.

Happy coding!