Scrabble_score


#1

This is the code that codecadamy gives when you click get code, and it works, but i was wondering why you needed the “if letter == leter:” line, could someone explain?

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

#2

The extra loop and the comparison are rudimentary code to protect against possible key errors if gibberish is inputed. In a perfect world,

for letter in word:
    total += score[letter]

would be adequate for all intents and purposes. If non-alpha inputs are given to the function, though, there will be key errors.

Consider the following,

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):
    try:
        total = 0;
        for letter in word.lower():
            total += score[letter]
        return total
    except KeyError:
        return "Input error!"
        
print (scrabble_score('xray'))     # 14
print (scrabble_score('XRAYS'))    # 15
print (scrabble_score('xray5'))    # Input error!

Up to this point we have not yet covered exception handling, though, so the above would not be a viable solution in this particular exercise since we are expected to work only with what we know so far.

https://repl.it/Klw1


#3

okay, thanks for explaining!


#4

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