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 trialRichárd Orbán
6,208 PointsWord Count counts characters instead of words
I found that all I had to do for it to work was to use the split() and lower() method on the string in the for loop, but I'd just like to know why that fixes it.
# 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(s):
s.split()
d = {}
for item in s:
if item in d:
d.update({item: d.get(item)+1})
else:
d.update({item: 1})
return d
1 Answer
Jennifer Nordell
Treehouse TeacherHi there, Richárd Orbán ! My guess here is that you ended up with something that looked a bit like this in your for
loop.
for item in s.lower().split():
This makes the string in question lower case and split on every iteration. And it's working from that string lowercased and split.
In your original code you had s.split()
. And it does split the string, but the results of that aren't ever assigned anywhere. They are just sort of floating around out there in Python limbo and will go up for garbage collection. Your original code that you posted here would have worked if you had both turned it to lower case and split it and assigned the values back into s
.
Instead of:
s.split()
You could have done:
s = s.lower().split()
Then when it evaluates s
in the for
loop it will be evaluating the correct thing. Again, when you do s.split()
it isn't overwriting the original value of s
so when it got down to the for
loop it's still in its original unsplit condition.
Hope this helps!
Richárd Orbán
6,208 PointsRichárd Orbán
6,208 PointsI didn't even think of that, thank you!