Scrabble_Score - Works for all words except 1


#1


https://www.codecademy.com/courses/python-intermediate-en-rCQKw/1/3?curriculum_id=4f89dab3d788890003000096

For Helix and other words the score is correct but for Xenophobia is 23 instead of 24


score = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2, 
         "f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3, 
         "l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1, 
         "r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4, 
         "x": 8, "z": 10}
         
def scrabble_score(word):
    score1 = 0
    new_word = word.lower()
    for key in score:
        if key in new_word:
            score1 = score1 + score[key]
    return score1
    
print scrabble_score("xenophobia")


#2

score is only a look-up list, not meant to be iterated. In your code, o is only counted once. Iterate the word, and look up each letter.


#4

I had this exact problem. As mtf said, your "o" in "xenophobia" is counted only once. So instead of iterating through the score dictionary first, I reversed the order so that my function would iterate through the characters in the word variable and check them against the dictionary:

def scrabble_score(word):
total = 0
for i in str(word.lower()):
if i in score:
total = score[i] + total
return total


#5

No need to re-cast to str since word is a string, else the .lower() call would raise an exception.


#6

I only did that because I later added .lower() in order to get past the "DuNe" word.

What do you mean by "raise an exception"?

Thanks!


#7

>>> (12345).lower()
Traceback (most recent call last):
  File "<pyshell#230>", line 1, in <module>
    (12345).lower()
AttributeError: 'int' object has no attribute 'lower'
>>>

The exception in this case is, AttributeError.


#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.