Computer Science Course - Scrabble Project

Hello, my program is returning 3 instead of 15, can someone please tell me what’s wrong with the code?

letters = [“A”, “B”, “C”, “D”, “E”, “F”, “G”, “H”, “I”, “J”, “K”, “L”, “M”, “N”, “O”, “P”, “Q”, “R”, “S”, “T”, “U”, “V”, “W”, “X”, “Y”, “Z”]

points = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 4, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10]

letter_to_points = {key:value for key, value in zip(letters, points)}

letter_to_points[’ '] = 0

def score_word(word):

point_total = 0

for letter in word:

point_total += letter_to_points.get(letter, 0)

return point_total

brownie_points = score_word(‘BROWNIE’)

print(brownie_points)

Looks suspect… Is the return inside the loop?

Aside

That is a lot of typing, while holding the shift key. Python treats a string as an iterable. We can traverse one just as easily as a list (or tuple). Using the the unpacking tool, (*) we can create a list from a string.

letters = [*'abcdefghijklmnopqrstuvwxyz']

We still end up with two lists in memory, the letters and the points. That on top of the dictionary we created from them. What if we put everything right inside the dict comprehension? The lists will evaporate and leave no memory footprint.

>>> letter_scores = {
  k: v for k, v in zip([
      *'abcdefghijklmnopqrstuvwxyz'
    ],
    [1,3,3,2,1,4,2,4,1,8,5,1,3,4,1,3,10,1,1,1,1,4,4,8,4,10]
  )
}
>>> letter_scores
{'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 4, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10}
>>> letter_scores.get('q', 0)
10
>>> 

So far we’ve shaved off our memory consumption, now we can leverage another iterator, map() to retrieve a word score.

>>> def get_word_score(word):
  return sum(map(lambda x: letter_scores.get(x, 0), [*word.lower()]))

>>> get_word_score('BROWNIE')
15
>>> get_word_score('brownie')
15
>>> get_word_score('BR0WNIE')  # note zero in place of oh.
14
>>> 

This is not what is expected of us at this stage, so keep thinking the way you do. Build around what you know. We’re only taking a sneak peek at what is just over the horizon in your learning path.

3 Likes

We never stop digging. And usually the outcome was staring us in the face, all along.

>>> letter_scores = dict(zip([
      *'abcdefghijklmnopqrstuvwxyz'
    ],
    [1,3,3,2,1,4,2,4,1,8,5,1,3,4,1,3,10,1,1,1,1,4,4,8,4,10]
  )
)
>>> letter_scores['q']
10
>>>