簡體   English   中英

Python 中的拼字游戲查找器

[英]scrabble word finder in Python

實施word_calculator方法以返回正確的拼字游戲單詞分數。 分數已經設置為可以使用並在字典中進行管理:

two = ['d', 'g']
three = ['b', 'c', 'm', 'p']
four = ['f', 'h', 'v', 'w', 'y']
five = ['k']
eight = ['j', 'x']
ten = ['q', 'z']

有了這些列表,我需要生成一個 function def word_calculator(word):我需要將一個字符串傳遞給該方法。 參數zoo應該return 12 ,而bus應該return 5

有人可以幫我制作 function 嗎?

與計算機科學中的許多問題一樣,如果您使用更好的數據結構,這將更容易解決。

正如您所擁有的那樣,您將必須為每個字母遍歷所有六個列表,檢查字母是否在每個列表中,然后以編程方式對每個列表的分數進行硬編碼,以便您可以將其添加到某個總數中。 這是很多工作,還有很多混亂的代碼。

但是,您可以改用字典。 字典可讓您將任何值 map 轉換為任何其他值。 所以,例如

x = {"A": 1, "B": 3}

意味着x["A"]是 1, x["B"]是 3,等等。


假設我們有一個字典,其中包含每個字母與其拼字游戲值的映射:

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": 1, "O": 1, "P": 3, "Q": 1, "R": 1, "S": 1, "T": 1, "U": 1, "V": 4, "W": 4, "X": 8, "Y": 4, "Z": 10}

我們如何找到"ZOO"的單詞得分? 我們需要:

  1. 遍歷每個字母
  2. 查找字母的分數(例如scores[letter]
  3. 將分數添加到一些運行總計中

例如,

total = 0
for letter in "ZOO" :
    total = total + score[letter]
print(total) # Prints 12

如果你想花哨一點,這也可以使用列表理解在一行中完成:

sum([scores[letter] for letter in "ZOO"])

延伸閱讀:

# the dictionary of scores to letter lists
score_letters = {
    2: ['d', 'g'],
    3: ['b', 'c', 'm', 'p'],
    4: ['f', 'h', 'v', 'w', 'y'],
    5: ['k'],
    8: ['j', 'x'],
    10: ['q', 'z']
}

# use `score_letters` to make a list from letters to score values
letter_scores = {letter: score for score, letters in score_letters.items() for letter in letters}
# equivalent to:
# letter_scores={}
# for score, letters in score_letters.items():
#     for letter in letters:
#         letter_scores[letter] = score

print('letter_scores =', letter_scores)


def word_calculator(word):
    # sum the scores of each letter in the word
    # `letter_scores.get(letter, 1)` means
    #     "get the value associated with the
    #     key `letter`, or if there is no such
    #     key in the dictionary, use the
    #     default value 1"
    return sum(letter_scores.get(letter, 1) for letter in word)


print('zoo', word_calculator('zoo'))
print('bus', word_calculator('bus'))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM