此代码用于根据作为参数给出的单词中包含的字母添加分数:
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()
n=0
scorer=0
while n<=len(word):
scorer = scorer + score[word[n]]
n+=1
return scorer
忽略我可能犯的任何其他语法错误。
答案 0 :(得分:3)
直接遍历word.lower()
的输出,而不是索引。另外,您可以使用sum
函数来计算所有字典查找的总和。
def scrabble_score(word):
return sum(score[c] for c in word.lower())
不太简洁的版本,仍然遵循原始代码的精神,仍然可以直接在word
上进行迭代。
def scrabble_score(word):
scorer = 0
for c in word.lower():
scorer = scorer + score[c] # or scorer += score[c]
return scorer
答案 1 :(得分:0)
您的代码正确。但是,有两个与样式有关的东西
在python中,字符串是字符的可迭代项,因此
scorer = 0
for letter in word.lower():
scorer += score[letter]
甚至更好,您可以使用列表理解
scorer = sum([score[letter] for letter in word.lower()])
答案 2 :(得分:0)
while n<=len(word):
将索引超出范围
您需要while n<len(word)
现有功能的工作副本
def scrabble_score(word):
word = word.lower()
n=0
scorer=0
while n<len(word):
scorer += score[word[n]]
n+=1
return scorer
正如其他人指出的那样,一种更简洁的方法是遍历单词的字符而不是索引
def scrabble_score(word):
word = word.lower()
scorer=0
for char in word:
scorer += score[char]
return scorer