scrabble_score 9:15 What is wrong with my code?


#1

Help, please

word = raw_input("Enter a word: ")
word = word.lower()

if word.isalpha() == False:
    print "Oops, you must input only letters!"

if word == "":
    print "Oops, input any word!"

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):
    result = 0
    for l in word:
        if l in score.keys():
            result += score[l]
            
    return result
    
print scrabble_score(word)


#2

Your code is returning the score for lower case letters only!

u = 1
e = 1

You're missing the uppercase letter scores. Try this instead:

def scrabble_score(word):
    result = 0
    for l in word.lower():
        if l in score.keys():
            result += score[l]

and take out the word = word.lower() you used earlier.


#3

Thank you, it works.

But why do my program show the correct answer?


#4

Not 100% sure but if I had to guess I'd say the console is bypassing everything else you've coded and only using the code written within the def scrabble_score(word) function, with their argument of word being DuNe. In your def function block you don't specify to convert to .lower() so the uppercase letters are being left out.

This would mean your user input where you ask first for the word then change to .lower() isn't taken into account.

That's just a guess though, it's the only way I can make sense of why your code works but the console gives an error.


#5

Your answer is using the .keys() method which is designed to return the keys (not the value) of each KV pair in a dictionary or what ever way you implement it on a dictionary. You should get the values by .get(). Here is my solution to this problem:

#Scrabble using dictionaries
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}
word = raw_input("Input your srabble word for a score now")

def scrabble_score(word):
    result = 0
    for w in word.lower():
        result += score.get(w, 0)    
    return result

#6

Yes, I think so too...
Anyway, thanks for the help


#7

You're welcome. Here was my working code

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):
    points = 0
    for i in word.lower():
        if i in score:
            points += score[i]
    return points