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 trialhuyen nguyen
850 PointsPlease help me debug this code
Thank a lot
# 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.
a_string=string.split()
def word_count(string):
my_dict = {}
string.lower()
new_str = string.split(' ')
for words in new_str:
if words in my_dict:
my_dict[word] += 1
else:
my_dict[word] = 1
return my_dict
print(word_count(string))
1 Answer
William Li
Courses Plus Student 26,868 PointsThe overall logic of your code is spot-on, however, there're some small bugs here and there.
- As Shaohui Yang points out, there're inconsistent uses of words and word in your code, this is obviously a typo.
-
string.lower()
, calling thelower()
method on string merely returns a copy of string, it has no impact on string's value. - Lastly,
.split(" ")
when a single empty space is provided as the argument to the split function, Python will only use one space as the delimiter for splitting the string into word. But if you call thesplit()
without argument, the function will use any number of consecutive spaces (" ", "\t" ... etc) as splitting delimiter. Doing so will give your split function little flexibility to handle the tricky test cases used by the grader.
def word_count(string):
my_dict = {}
new_str = string.lower().split() # combine this and previous line into one
for word in new_str:
if word in my_dict:
my_dict[word] += 1
else:
my_dict[word] = 1
return my_dict
def word_count(string):
my_dict = {}
for word in string.lower().split(): # or you can combine 3 lines into one, making it one less local variable
if word in my_dict:
my_dict[word] += 1
else:
my_dict[word] = 1
return my_dict
hope it helps.
Shaohui Yang
5,009 PointsShaohui Yang
5,009 Pointswords => word you have a typo