值将无法正确计算

时间:2019-06-14 15:39:53

标签: python

我正在尝试列出列表,然后使用函数计算拼字游戏得分。我认为那部分工作了。

然后,我需要通过另一个函数来运行列表,该函数创建一个以单词为键,而拼字游戏得分函数为值的字典。

它可以工作,但是它似乎可以单独调用,但是似乎只调用了score中的第一个字母。

我在CC的Python第五周了,所以我们没有使用递归或任何其他高级方法,这是针对函数章节的。

请让我知道我在做什么错,以便我可以从中学到东西。

我已经多次重写了这些功能,并在纸上“遍历”了这些功能,因此显然我缺少一些基本知识。

word_dict = dict()
def computeScrabbleScore(word_list):
    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':8, 'w':4,
                 'x':8, 'y':4, 'z':10}

    for word in word_list:
        score = 0
        word = word.lower()
        #print(word)
        for letter in word:
            score += letter_values[letter]  
        #print(score,'*')
        return score

def wordScore(word_list):
# Use the variable word_dict for the (word,word score) dictionary.
    for word in word_list:
        word_dict[word] = computeScrabbleScore(word)
    return word_dict

wlist = 
['Half','a','league','half','a','league','Half','a','league','onward',
     'All','in','the','valley','of','Death','Rode','the','six','hundred',
     'Forward','the','Light','Brigade','Charge','for','the','guns','he','said',
     'Into','the','valley','of','Death','Rode','the','six','hundred']
#word_dict = wordScore(word_list)
#t = computeScrabbleScore(wlist)
#print(score)
x = wordScore(wlist)
print(x)

1 个答案:

答案 0 :(得分:0)

它认为score变量应该在循环之前:

word_dict = dict()
def computeScrabbleScore(word):
    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':8, 'w':4,
                     'x':8, 'y':4, 'z':10}

    score = 0
    word = word.lower()

    for letter in word:
        score += letter_values[letter]
    #print(score,'*')
    return score

def wordScore(word_list):
    # Use the variable word_dict for the (word,word score) dictionary.
    for word in word_list:
        word_dict[word] = computeScrabbleScore(word)
    return word_dict

wlist = ['Half','a','league','half','a','league','Half','a','league','onward',
     'All','in','the','valley','of','Death','Rode','the','six','hundred',
     'Forward','the','Light','Brigade','Charge','for','the','guns','he','said',
     'Into','the','valley','of','Death','Rode','the','six','hundred']
#word_dict = wordScore(word_list)
#t = computeScrabbleScore(wlist)
#print(score)
x = wordScore(wlist)
print(x)

输出:

{'Death': 9, 'Charge': 12, 'in': 2, 'Forward': 14, 'Brigade': 11, 'said': 5, 'for': 6, 'onward': 10, 'Half': 10, 'hundred': 12, 'guns': 5, 'Light': 9, 'half': 10, 'six': 10, 'he': 5, 'a': 1, 'league': 7, 'All': 3, 'valley': 16, 'of': 5, 'Into': 4, 'Rode': 5, 'the': 6}