我一直在尝试在项目Euler上做问题22,但我似乎无法得到正确的答案或看到我的代码有任何问题。我复制并粘贴了txt文件的内容,而不是直接从我的代码中访问它。
https://projecteuler.net/problem=22
namelst = open(names.txt)
namedict = {}
alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
for x in namelst:
score = 0 #creates score for each word
for y in x:
score += alphabet.index(y.lower())+1 #adds alphabetic score for each letter
namedict[x] = score
namedict = sorted(namedict.values()) #creates list of scores ordered by size
scoresum = 0
for x in namedict:
index = namedict.index(x)+1
scoresum += x*index #multiplies score sum by order in the list
print(scoresum)
不幸的是,这给了我985466567
的答案,而871198282
是正确答案。我的代码或方法有错误吗?
如果有人能提供帮助那就太棒了!
答案 0 :(得分:0)
你很亲密。您的代码存在一些问题:
namedict
不是字典,而是列表。enumerate
。结合这些元素:
from string import ascii_lowercase
namelst = ['abc', 'def', 'ghi']
namedict = {}
alphabet = ascii_lowercase
for x in namelst:
score = 0
for y in x:
score += alphabet.index(y.lower())+1
namedict[x] = score
namelist = sorted(namedict.items(), key=lambda x: x[1])
print(namelist)
# [('abc', 6), ('def', 15), ('ghi', 24)]
scoresum = 0
for idx, x in enumerate(namelist, 1):
scoresum += idx*x[1]
print(scoresum)
# 108, i.e. 6 + 30 + 72