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
Manfredi Martorana
19,470 Pointsword_count
Hi guys,
I'm having some trouble in this code challenge.
In particular I can not count the number of times that the words appear in the string I pass.
My code:
def word_count(str):
my_list = str.split()
word_dict = {}
k = 1
for word in my_list:
if word in word_dict:
word_dict[word] = k + 1
else:
word_dict[word] = 1
return word_dict
Thank you for the help!
3 Answers
Kenneth Love
Treehouse Guest TeacherFirst off, it's not a great idea to use str as a variable name since that's the class/type that strings belong to. You'll make it so you can't get to string methods, sometimes, and then wonder if you're going insane. Trust me, been there.
Secondly, your highest count for any word is 2 due to how you're doing your value assignment for each key. You should be incrementing the existing count by 1, if the word is already in the dictionary, or setting it to one if it's not. There are a couple of other ways of doing this, too, if you want to look around the forums or look up the docs for dict.setdefault().
Good luck!
Manfredi Martorana
19,470 PointsOk, well. I used str as argument, because I want to pass a variable that can only be a "string". Maybe It is not so correct.
On the other hand, I fixed it, just removing the variable 'k', and incrementing by one.
Thank you so much!
Kenneth Love
Treehouse Guest TeacherYou can't enforce variable types in function declarations.
Manfredi Martorana
19,470 PointsYes, I figured out ;).
So, I pass everything except methods, and then when I call the function I can use everything, isn't it?
Kenneth Love
Treehouse Guest TeacherGive your function exactly what it needs. Functions can take anything as an argument: variables, functions, classes, raw data, etc. Don't pass libraries or outside functionality to your function, though. Just import that into the file and use it.