简体   繁体   English

如何确定存储在文件中的最大拼字游戏分数?

[英]How to determine the maximum scrabble score stored in a file?

I got a list of points for each letter:我得到了每个字母的分数列表:

SCRABBLES_SCORES = [(1, "E A O I N R T L S U"), (2, "D G"), (3, "B C M P"),
                    (4, "F H V W Y"), (5, "K"), (8, "J X"), (10, "Q Z")]

And in file I have to find word with the highest score在文件中我必须找到得分最高的单词

I have a problem, because I don't know how to examine new line.我有一个问题,因为我不知道如何检查新行。 I tried this, but its never ending loop:我试过这个,但它永无止境的循环:

max = 0
help = 0
file = open("dictionary.txt", "r")
for line in file:
    for l in line:
        while(l != '\n'):
            help += LETTER_SCORES.get(l)
            if(help > max):
                max = help
            else:
                continue
    help = 0

print(max)

Does anybody know what Im doing wrong?有人知道我做错了什么吗?

[ Edit ] Mapping for dictionary: [编辑] 字典映射:

LETTER_SCORES = {letter: score for score, letters in SCRABBLES_SCORES
                    for letter in letters.split()}

The while loop is causing your error. while循环导致您的错误。

Say the first line began with the letter 'a' , then the condition l != '\\n' will be true and won't change during the iterations of the while loop, so you get stuck there.假设第一行以字母'a'开头,那么条件l != '\\n'将为真,并且在 while 循环的迭代过程中不会改变,所以你会卡在那里。

You don't need the while loop altogether.您完全不需要while循环。

Try using generator comprehensions for a cleaner and clearer answer:尝试使用生成器推导式以获得更清晰、更清晰的答案:

words = ['foo', 'bar', 'baz']  # this simulates the words in your file

max(sum(LETTER_SCORES[c.upper()] for c in word) for word in words)  # returns 14 for 'baz'

You can read your file as follows:您可以按如下方式阅读您的文件:

with open("dictionary.txt") as f:
    words = list(f)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM