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 trialChris Adamson
132,143 PointsBug in the quiz
There appears to be a bug in this quiz, if you look at the comments, even the resulting dictionary is wrong, I shows up twice, and do only once. The code below should work but fails upon submittal.
# E.g. word_count("I do not like it Sam I Am") gets back a dictionary like:
# {'i': 2, 'do': 2, 'it': 1, 'sam': 1, 'like': 1, 'not': 1, 'am': 1}
# Lowercase the string to make it easier.
def word_count(sentence):
words = sentence.lower().split(" ")
ret_val = {}
for word in words:
if ret_val.has_key(word):
ret_val[word] = ret_val[word] + 1
else:
ret_val[word] = 1
return ret_val
1 Answer
William Li
Courses Plus Student 26,868 Pointshi, Chris Adamson
Basically, 1 of the 2 problems in your code is the " " argument in the split() function, in doing so it restricts the split function into using only 1 space char as delimiter; we should be calling the split() function with no argument, this by default will use any number of consecutive white spaces (" ", "\t" ... etc) as delimiter, allowing the split() function to have the flexibility of handling some tricky test cases the grader might use.
Additionally, dict.has_key()
that you used in your code has been removed in Python 3.
Here's the corrected version of your code
def word_count(sentence):
words = sentence.lower().split()
ret_val = {}
for word in words:
if word in ret_val:
ret_val[word] = ret_val[word] + 1
else:
ret_val[word] = 1
return ret_val
I indented the code using 4 spaces to comply with PEP8 Python style guide. Cheers.
Jason Anello
Courses Plus Student 94,610 PointsJason Anello
Courses Plus Student 94,610 Pointsfixed code formatting