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 trial

Python Python Collections (2016, retired 2019) Dictionaries Word Count

Lukas Straumann
seal-mask
.a{fill-rule:evenodd;}techdegree
Lukas Straumann
Python Web Development Techdegree Student 9,588 Points

Hi. I think my code does the right thing, but it doesn't get accepted. Why that?

Hi. I think my code does the right thing, but it doesn't get accepted (ok, it is terrible code, but still). Can you help me to find out why?

wordcount.py
# 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}
def word_count(aString):
    aString = aString.lower()
    word = ""
    word_list = []

    while True:
        if "  " in aString:
            aString = aString.replace("  ", " ")
        else:
            break

    if aString[-1] == " ":
        alist2 = list(aString)
        del alist2[-1]
        aString = "".join(alist2)

    if aString[0] == " ":
        alist2 = list(aString)
        del alist2[0]
        aString = "".join(alist2)

    for letter in aString:
        if letter != " ":
            word += letter
        else:
            word_list.append(word)
            word = ""
    word_list.append(word)

    word_count={}
    for word in word_list:
        if word not in word_count:
            word_count[word] = 1
        else:
            word_count[word] += 1
    return word_count

2 Answers

Ryan Cross
Ryan Cross
5,742 Points

The bulk of your code is doing the work of the line

str_list=lower.split()

understand what that line means and you won't have to go through all this trouble building something that exists already!

Ryan Cross
Ryan Cross
5,742 Points

you bet have fun and work hard!