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 trialAbhishek Dokania
893 PointsNot sure why this code is now passing on Treehouse platform. It ran fine on local machine
Please advise
# 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(str1):
list1 = str1.split()
for i in range(len(list1)):
list1[i] = list1[i].lower()
count_dict = {}
for i in range(len(list1)):
if list1[i] not in count_dict:
count_dict[list1[i]] = 1
j= i+1
while (j < len(list1)):
if list1[j] == list1[i]:
count_dict[list1[i]]= count_dict[list1[i]]+1
j=j+1
return(count_dict)
1 Answer
Kenneth Love
Treehouse Guest TeacherHmm, you're doing a lot of work here. More than I would say is required for this particular challenge.
if list1[i] not in count_dict:
count_dict[list1[i]] = 1
j= i+1
while (j < len(list1)):
if list1[j] == list1[i]:
count_dict[list1[i]]= count_dict[list1[i]]+1
j=j+1
I'm not 100% certain, but won't this cause each word to be counted twice? The first time it's encountered, it's set as occurring once. Then you're going through the list of words again and, if you find it, incrementing the count. Do I have that right?