Creating a python scrabble function that takes a string as input and returns a score for that word
本问题已经有最佳答案,请猛点这里访问。
嗨,我正在编解码器练习9/15。目标是创建一个以字符串作为输入的拼字函数,然后返回该单词的分数。
他们给你一本字典作为开始,这是我在谷歌上搜索"如何循环使用字典并添加值"后得到的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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} 1) total = 0 # takes your input word value and saves it to total 2) def scrabble_score(x): # defining function name 3) for i in score.values(): # loops through score 4) total += i # sums up your input key value 5) return i |
此代码不断引发局部变量total错误。
这是否意味着总变量不适用于拼字得分(x)函数?
你需要把
1 2 3 4 5 6 7 8 9 10 11 | SCORES = {"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 scrabble_score(word): total = 0 for letter in word: total += SCORES[letter] return total |
另一种方法是,记住未来:
1 2 | def scrabble_score(word): return sum(SCORES[letter] for letter in word) |
当你使用字典时,你不需要循环浏览它。访问字典值的方法非常简单。例如,在字典中,您有:
1 2 3 4 5 | 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} |
如果你想得到"a"的值,你需要做的就是:
1 2 3 | test='b' total=score[test] print(total) |
你会得到:
1 | 3 |
您所要做的就是循环遍历您拥有的字符串,调用每个字母并将它们添加到总计中。在开始之前,确保将总数设置为
您有
另外,您的循环似乎没有考虑
然后返回一个索引而不是总计。