字典键,添加它们的值

时间:2017-11-09 07:28:38

标签: python-3.x dictionary

当我尝试从字典中添加以下内容时,它会显示不匹配的测试用例输出

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 dic_add(text):
    lower = text.lower()
    total = 0
    for c in lower:
        total += total + score[c]
    return total
dic_add("Pie")

应返回 5 ,但输出为 15

任何人的帮助

预期输出: 5

获得的输出: 15

2 个答案:

答案 0 :(得分:2)

通过执行total += total + score[c],您将增加total两次。仅使用total += score[c]

total += score[c]已经意味着total = total + score[c]

答案 1 :(得分:1)

错误在这一行:

total += total + score[c]

使用:

total = total + score[c]

或:

total += score[c]