因此,我有一個包含整個字母表的字典,以字符為鍵,以 1-9 之間的不同數字為值。
SCRABBLE_LETTER_VALUES = {
'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}
我想知道的是如何,給定一個詞,找到與鍵關聯的相應鍵值的總和,即。單詞中的字符。
例如
abc
將產生 7。
我寫了以下代碼
def get_word_score(word,n):
"""Assumes the word is correct and calculates the score, will need to handle strings with mixed cases"""
sum = 0
word_low = word.lower()
for i in word_low:
sum = LETTER_VALUES[i]
return sum
任何幫助將不勝感激 :)
uj5u.com熱心網友回復:
似乎您呼叫的是錯誤的dictionary:它應該是 SCRABBLE_LETTER_VALUES(假設它是在上面全域定義的)。其次,不確定n您的函式簽名中的作用是什么?因為從來沒用過?!
或者,您可以簡化處理以僅使用generator expression并sum一次性傳遞給:
請注意 - 在 Python 中,字串(單詞)也是一個可以迭代的互動物件。
LETTER_VALUES 是您的來源。字典。
def get_word_score(word):
return sum(LETTER_VALUES[ch] for ch in word.lower())
In [4]: get_word_score("ABBA")
Out[4]: 8
In [5]: get_word_score("Dr")
Out[5]: 3
In [6]: get_word_score('Zoo')
Out[6]: 12
uj5u.com熱心網友回復:
你的代碼幾乎是正確的。我只是稍微修改了你的代碼,以便你了解如何改進你的代碼,如下:
- 看起來functin 'get_word_score' 不需要引數'n',所以我洗掉了它。
- 在 get_word_score 函式中,我將“LETTER_VALUES”更改為“SCRABBLE_LETTER_VALUES”。
- 我將變數名稱更改
sum為 'sum_of_val' 原因sum是@daniel-hao 評論的內置函式
def get_word_score(word):
"""Assumes the word is correct and calculates the score, will need to handle strings with mixed cases"""
sum_of_val = 0
word_low = word.lower()
for i in word_low:
sum_of_val = SCRABBLE_LETTER_VALUES[i]
return sum_of_val
SCRABBLE_LETTER_VALUES = {
'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}
result = get_word_score('abc')
print(result)
# 7
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/357320.html
