Reputation: 19
Can someone break down the individual components that make up scrabble_score:
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):
return sum([score[x] for x in word.replace(" ", "").lower() if x in score])
Upvotes: 0
Views: 690
Reputation: 1
you can use this code for solution
total_score variable is to sum letter score. the score[char.lower()] is for code that will work even if the letters you get are uppercase, lowercase, or a mix
def scrabble_score (word):
total_score=0
for char in word:
total_score+=score[char.lower()]
return total_score
Upvotes: 0
Reputation: 11075
broken down (in bold)...
return sum([score[x] for x in word.replace(" ", "").lower() if x in score])
removes all spaces and converts to all lower case
return sum([score[x] for x in word.replace(" ", "").lower() if x in score])
for each letter after removing spaces and converting to lower case
return sum([score[x] for x in word.replace(" ", "").lower() if x in score])
if that letter is in the score dictionary
return sum([score[x] for x in word.replace(" ", "").lower() if x in score])
get the score for that letter and add it to a list
return sum([score[x] for x in word.replace(" ", "").lower() if x in score])
after getting the score for each letter, add up the sum of the resulting list of values and return
Upvotes: 0
Reputation: 54223
The structure is a list comprehension. This is a terse way of creating a list from an iterable. See below where the 1
s are list comps and the 2
s are traditional for
loops.
result1 = [some_value for element in iterable]
# where the group of "value" statements is the final list
result2 = []
for element in iterable:
result2.append(some_value)
example1 = [x**2 for x in range(10)] # [0**2, 1**2, 2**2, ..., 9**2]
example2 = []
for x in range(10):
example2.append(x)
This particular listcomp is using a dict lookup (score[x]
) as the value of the list, where x
is each element of word.replace(" ", "").lower()
. It also uses a conditional filtering statement at the end to make sure it only selects those elements where x
is in score
(so something like it's
doesn't fail on the '
.)
Wrapped around it is sum
, which simply adds all the numbers in a list and gives the result.
Upvotes: 1