我得到了每个字母的要点列表:
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")]
在文件中,我必须找到得分最高的单词
我有一个问题,因为我不知道如何检查新行。 我试过了,但是循环永无止境:
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)
有人知道我在做什么错吗?
[编辑]字典映射:
LETTER_SCORES = {letter: score for score, letters in SCRABBLES_SCORES
for letter in letters.split()}
答案 0 :(得分:1)
while
循环正在引起您的错误。
假设第一行以字母'a'
开头,那么条件l != '\n'
将为true,并且在while循环的迭代过程中不会改变,因此您会陷入困境。
您完全不需要while
循环。
答案 1 :(得分:1)
尝试使用generator comprehensions以获得更清晰的答案:
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'
您可以按以下方式读取文件:
with open("dictionary.txt") as f:
words = list(f)