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 trialac ggacac
Python Web Development Techdegree Student 20,895 PointsWhy my code did not work?
I have tried this code on an online compiler and my code worked. However when I use it for the exercise, it does not work.
# 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(st):
dic = {}
copy = {}
arr = st.split()
for word in arr:
if len(dic) == 0:
dic[word.lower()] = 1
continue
for new in dic:
copy[new] = dic[new]
for key in dic:
if key == word.lower():
copy[key] += 1
break
else:
copy[word.lower()] = 1
for new_1 in copy:
dic[new_1] = copy[new_1]
return dic
1 Answer
Istvan Nonn
2,092 PointsI am not sure (just yet) how the code checker works, but most like there is a pattern or a strict way / order the code needs to be written. Anyway, I'll keep looking around for other solutions, meanwhile if anyone can help to solve the mystery will be much appreciated:
def word_count(sentence):
sentence = sentence.lower().split(" ")
words = {}
for word in sentence:
number_of_times = sentence.count(word)
words[word] = number_of_times
return words
Istvan Nonn
2,092 PointsOnce again, Jennifer Nordell saved me.
Istvan Nonn
2,092 PointsIstvan Nonn
2,092 PointsFor sure your code gives back the expected result, however I will highly suggest to rewrite your code. It is good as a first approach, but than just try to clean it up and think if you can make it shorter. There are way too many for loops and if statements.