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

Ming How Chai
Ming How Chai
2,040 Points

Hi, may someone help me to check what's wrong with my code?

When I ran the testcase on the mission in Idle, it returned expected output. I don't know why my code was not accepted.

"Hmm,didn't get the expected output..."

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(string):
    word_list = string.split()
    dictionary = {}
    for word in word_list:
        l = len(word)
        i = 0
        count = 0
        while l+i <= len(string):
            if word == string[i:l+i]:
                count += 1
            i += 1
        dictionary[word.lower()] = count
    return dictionary

1 Answer

Stuart Wright
Stuart Wright
41,119 Points

I think the error is that you don't do the lower casing until the end. If you pass a more complicated string in, it won't group words together that have different cases in the input string. So although it works for the example string given in the challenge, it will not work for, say:

"I do not like it Sam I Am I I am i sam"

Try it and you'll see that your function gives the wrong output.

I also think that your function is more complex than it needs to be. A much simpler solution to the problem is as follows:

def word_count(string):
    string = string.lower()
    string = string.split()
    word_count_dict = {}
    for word in string:
        if word in word_count_dict.keys():
            word_count_dict[word] += 1
        else:
            word_count_dict[word] = 1
    return word_count_dict
Ming How Chai
Ming How Chai
2,040 Points

thanks for pointing out.