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 trialKen LaRose
Python Web Development Techdegree Student 21,982 PointsPython word_count function isn't passing - what's wrong?
I wrote this word_count function to accept a string and return a dictionary filled with the lowercase version of each word and the integer count of each word in the original string. I can't pass the code challenge, but every string I send through this function comes out right... I think... Can anybody see what's wrong with this solution?
# 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):
words = arg.lower().split(' ')
count = {}
for word in words:
if word in count:
count[word] += 1
else:
count[word] = 1
return count
1 Answer
eck
43,038 PointsI think this line might be your problem: arg.lower().split(' ')
, which should probably just be arg.lower().split()
.
The reason for this is that splitting a string on spaces would treat a double space as a word, whereas calling .split
without an argument will ensure empty spaces are all trimmed.
Ken LaRose
Python Web Development Techdegree Student 21,982 PointsKen LaRose
Python Web Development Techdegree Student 21,982 PointsErik, you are the man! That was it. Thank you very much - that was driving me crazy!
eck
43,038 Pointseck
43,038 PointsYeah, that was pretty subtle; glad it worked :D