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

Answer works locally, but won't pass on the challenge

This is my code:

# 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(arg):
    split = arg.lower().split(' ')
    word_dict = {}

    for word in split:
        if word in word_dict:
            word_dict[word] += 1
        else:
            word_dict[word] = 1

    return word_dict

This is the error:

Bummer! Hmm, didn't get the expected output. Be sure you're lowercasing the string and splitting on all whitespace!

I tried the function locally with the example they provide and I get the following output:

{'this': 1, 'test': 2, 'string': 2, 'is': 1, 'only': 1, 'a': 1}

What am I missing here?

1 Answer

The issue is that the challenge expects your code to split on all whitespace. A space is a type of whitespace but things line new lines, tabs, multiple spaces in a row and the like are also examples of whitespace. This is not an issue that is apparent based on their test input because that only contains standard spaces.

The split method will actually split on all whitespace by default if you don't pass it any argument, so if you simply remove the string you pass to it like this:

def word_count(arg):
    split = arg.lower().split() # Split without specifying argument
    word_dict = {}

    for word in split:
        if word in word_dict:
            word_dict[word] += 1
        else:
            word_dict[word] = 1

    return word_dict

Then your code will be accepted.

Thank you for the explanation Arden, that explains it well.