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 trialTan Yang
13,163 Pointsplease help what is the problem of my code
help
# 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(string):
string_list = string.split(" ")
length = len(string_list)
new_string_list = []
for word in string_list:
new_string_list.append(word.lower())
new_dict = {}
for lowered_word in new_string_list:
count = 0
for i in range(length):
if lowered_word == new_string_list[i]:
count += 1
new_dict[lowered_word] = count
return new_dict
3 Answers
Martynas Matimaitis
10,480 PointsHi,
can you specify what do you mean by wrong? I added a function call with a variable and the output seems to be correct in few tests I ran:
def word_count(string):
string_list = string.split(" ")
length = len(string_list)
new_string_list = []
for word in string_list:
new_string_list.append(word.lower())
new_dict = {}
for lowered_word in new_string_list:
count = 0
for i in range(length):
if lowered_word == new_string_list[i]:
count += 1
new_dict[lowered_word] = count
return new_dict
count = word_count("Ha ha ha ha HA HA HA hi Hi HI")
print(count)
Output: {'ha': 7, 'hi': 3}
Tan Yang
13,163 Pointsgreat, thanks Grigorij. it works.
Grigorij Schleifer
10,365 PointsHi Tan, your code works if you remove the quotation marks from the split method. Just split the string with whitespace which is the default one of the split option.