Reputation: 235
I am creating a program that scores a scrabble game. For the part that scores the word, it uses a dictionary with the Scrabble letter values:
letter_val = {" ": 0, "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": 1, "o": 1, "p": 3, "q": 10, "r": 1, "s": 1, "t": 1, "u": 1, "v": 4, "w": 4, "x": 8, "y": 4, "z": 10}
It takes a word as input and loops through it with the dictionary, assigning the sum to a value. I tried something along the lines of:
value = sum(letter_val[i.lower() for i in word])
or just:
value = letter_val[i.lower() for i in word
Will I have to make a whole for loop or is there anything I'm missing in the way I'm doing it?
Upvotes: 1
Views: 88
Reputation: 140
When you iterate through a string/list inline, it returns an array.
>>> x = "many"
>>> y = [i for i in x]
>>> y
['m', 'a', 'n', 'y']
While looking up a value in a dictionary, it's done just like index based accessing on a list.
>>> a = {"x": 1, "y": 2, "z": 3}
>>> b = a["x"]
>>> b
1
In your case, you're putting together both of the above. So, first off, make a list from the scores equivalent to the letters in the word
>>> letter_val = {" ": 0, "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": 1, "o": 1, "p": 3, "q": 10, "r": 1, "s": 1, "t": 1, "u": 1, "v": 4, "w": 4, "x": 8, "y": 4, "z": 10}
>>> word = "abc"
>>> scores = [letter_val[i] for i in word]
>>> scores
[1, 3, 3]
Then find the sum of values of the list
>>> value = sum(scores)
>>> value
7
Upvotes: 1