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 trialsonny unverferth
Python Web Development Techdegree Student 2,889 Pointsword count
There has got to be an easier way to do this. Im assuming this is bad practice (nested while/if ect). Can someone show me a better way? I feel like I went too deep down a long and confusing rabbit hole to find the solution. Took way too long. My code tends to do this alot. If anyone has any tips for thinking differently I would really appreciate it =)
MUCH LOVE!
# 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(str_arg):
words = str_arg.lower().split()
new_dict = {}
for word in words:
pos = 0
i = 0
while len(words) > pos:
if word == words[pos]:
pos += 1
i += 1
else:
pos += 1
new_dict[word] = i
return new_dict
1 Answer
Kenneth Love
Treehouse Guest TeacherWalk through your code, explaining it in your native language. I know that helps me a lot.
I'll say this. You don't need the while loop, pos
or i
. If the word is in the dictionary, what should you do? If it's not, what should you do then? Any time you find yourself using an index variable in Python, where you're keeping track of your current position in a list, you're probably doing something you don't need to do.
sonny unverferth
Python Web Development Techdegree Student 2,889 Pointssonny unverferth
Python Web Development Techdegree Student 2,889 PointsYou're the man! I will keep this in mind going forward. Thank you. Should I post this kind of question elsewhere? I feel others may not find my questions useful enough to create an entire post about it..
Kenneth Love
Treehouse Guest TeacherKenneth Love
Treehouse Guest TeacherYour post/question is fine. Leave 'em.