[英]Python - Scoring a list of words using a dictionary of Scrabble letter values
对不起,如果这一切都很简单,我是编码新手。
我得到了一个单词列表,即
my_words = [ 'Apple", 'banana', 'Grape', 'orange' ]
我还得到了一个字母值字典,
letter_value = {'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':8, 'w':4, 'x':8, 'y':4, 'z':10}
我必须
创建一个函数,它接受一个单词并计算该单词的拼字游戏分数,我这样做了:
def scrabblescore(words):
total = 0
for letter in word:
total += letter_value[letters]
return total
当我尝试时, print(scrabblescore("myscore")
它工作正常
我不知道该怎么做
编写一个函数,该函数将获取整个单词列表,遍历该列表,并使用第一个函数计算列表中每个单词的得分并制作字典,例如
{'apple': 20, 'banana':10} etc.
提前谢谢大家
我不打算把完整的代码放在这里(这是给你弄明白的),但我会告诉你你应该做什么。
1:设置字典变量。
2:遍历值。 对于 my_words 中的每个单词,请执行以下操作:
3:遍历字母。 对于 my_words 中 word 中的每个字母,请执行以下操作:
4:在字典中查找字母的键值。 将其添加到临时变量中。
5:设置word为key,临时变量为value。
首先修复您的方法,关于变量的名称,并使用.lower()
处理大写字母
def scrabble_score(word):
total = 0
for letter in word:
total += letter_value[letter.lower()]
return total
然后对于单词列表,您可以使用 dict-comprehension 或经典的 for 循环
def scrabble_score_words(words):
return {word: scrabble_score(word) for word in words}
def scrabble_score_words(words):
result = {}
for word in words:
result[word] = scrabble_score(word)
return result
这是一个 foreach 字符循环:
for element in string_name:
你可以让它像:
def scrabble_score(word):
total = 0
for letter in word:
# hit here
# 1. added lower() to make the letter lowercase
# 2. IMPORTANT use letter
total += letter_value[letter.lower()]
return total
def scrabble_score_list(words):
"""take a list of the words"""
# Just a wrapper for the first function
rd = {}
for x in words:
rd[x] = scrabble_score(x)
return rd
我喜欢做家庭作业。 我求你学习; 不只是复制。
""" Yet another SO homework assignment """
letter_value = {'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':8, 'w':4, 'x':8, 'y':4, 'z':10}
def scrabble_score(word):
"""
For a specific word, calculate the scrabble score of that word.
:returns: The numeric scrabble score of a word.
"""
total = 0
for letter in word.lower():
total += letter_value[letter]
return total
def scrabble_dict(word_list):
"""
A function that will take the whole list of words, iterate over the list,
and use the scrabblescore() to compute the score of each word in the list
and make a dictionary like {'Apple': 20, 'Banana':10}
"""
word_dict = {}
for word in word_list:
score = scrabble_score(word)
word_entry = {word: score}
word_dict.update(word_entry)
return word_dict
def main():
""" Test out the scrabble dictionary """
scrabble_dictionary = {}
word_set_1 = ['Apple', 'banana', 'Grape', 'orange']
scrabble_dictionary.update(scrabble_dict(word_set_1))
word_set_2 = ['Orange', 'Pear', 'Grape', 'Pineapple', 'Xerox']
scrabble_dictionary.update(scrabble_dict(word_set_2))
print(scrabble_dictionary)
if __name__ == "__main__":
main()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.