Scrabble_score - really starting to struggle


#1



So I have used the Q&A resources a lot in this course, and it's making me think I should start Python over to get more practice. Some I'm sailing through, some I don't even know where to start.


Oops, try again. Did you create a function called scrabble_score? Your code threw a "global name 'd' is not defined" error.


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):
    for i in word:
        word == d[key] + key
    return word


#2

Missing if, but that is no matter. We do not need a conditional test, just look up the score for each letter in the word and add it to a running total.

total = 0    # initialize to zero
for letter in word.lower():
    total += score[letter]
return total

Make sense?


#3

Okay, so add total to score[letter], which is the dictionary key, right?

I'm trying to piece together what I'm learning so I can offer the simplest solution, but I don't want to take shortcuts that screw up my code, if that makes sense.


#4
add score[letter] to total

Correct. The keys are only in lowercase, so the word is iterated in lowercase.

Test the code and see if the results match what you expect. Study the code so you can explain it to yourself. Test your skills by going back a week later and reseting the code for a do-over. See how well your understanding sticks.


#5

I can see there are possibilities of doing this in few lines of code so I always check on the forums to see if there is a better way. But perhaps the way I did, seeing as its done in more albeit simpler steps may shed some light on this.

def scrabble_score(word):       #define a new function
    finalscore = 0                    #finalscore variable to hold answer
    newword = word.lower()      #make a new word that is lowercase
    for i in newword:                #iterate through given word in lower case
        finalscore += score[i]     #add the value of key to variable finalscore
    return finalscore                #return finalscore outside the foor loop

I now see that I could have skipped the step of making a new variable called "newword" and simply done this:

def scrabble_score(word):       #define a new function
    finalscore = 0                    #finalscore variable to hold answer
    for i in word.lower():                #iterate through given word in lower case
        finalscore += score[i]     #add the value of key to variable finalscore
    return finalscore

which would have removed 1 line of code and done the same. so thank you for showing that.

hope this helps someone


#6

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