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 trialAndrey Misikhin
16,529 PointsWhy it doesn't work?
I'm tried different variants. Its works in console on my PC, but here the bummer appers.
First:
def word_count(string): dic = {} arr = string.lower() arr = arr.split(" ") counter = 1 while len(arr) > 0: item = arr.pop(0) while item in arr: item = arr.pop(arr.index(item)) counter += 1 else: dic[item] = counter counter = 1 return dic
Second:
def word_count(string): dic = {} arr = string.lower() arr = arr.split(" ") for item in arr: dic[item] = arr.count(item) return dic
# 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):
dic = {}
arr = string.lower()
arr = arr.split(" ")
counter = 1
while len(arr) > 0:
item = arr.pop(0)
while item in arr:
item = arr.pop(arr.index(item))
counter += 1
else:
dic[item] = counter
counter = 1
return dic
2 Answers
James Reinhold
12,361 Pointsdef word_count(string):
string = string.lower()
word_dict = {}
word_list = string.split()
for sel_word in word_list:
count = 0
for word in word_list:
if sel_word == word:
count +=1
word_dict[sel_word] = count
return word_dict
The difference is that .split(" ") splits only on spaces and .split() splits on all whitespace. Whitespace includes spaces, tabs, newlines, vertical spaces, etc.
The challenge expects you to split on all whitespace
Andrey Misikhin
16,529 PointsThank you, James! Now understood the meaning of words "all whitespace" :)