9.scrabble_score


#1

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

Oops, try again. Your function fails on scrabble_score("pie"). It returns "3" when it should return "5".

please help~


#2

a function ends the moment a return keyword is reached, which happens in the in the first run of your loop. Place the return at the same indent level as the for loop, this way, the whole loop can run, instead of just once


#3

Guys, please explain me, it's look a simple but I am not sure that I understand it fully step by step:

def scrabble_score(word):
    ans=0 # why int not list or str here?
    for i in word.lower(): #iterate every letter at word. Understand.
        ans+=score[i] #to ans adds every key from score? What exctly score[i] did? 
    return ans

Thanks!


#4

because the store score in ans? Bit in-effective to use a list or string to store a number.

score is the dictionary, we can can use the key (i) to access the value which belongs to a key.


#5

Thanks! And how to access the key if I need?


#6

you can write a for loop:

for i in name_dictionary:
   print i // prints key
   print name_dictionary[i] // prints value belonging to key

there are also build in function, for python2 this is items and iteritems (which is below it)


#7

Thank you very much! You help me 2 times today! :slight_smile:


#8

@boardwhiz33711 your _return _ statement needs to be outside the loop.