我正在尝试解决Euler项目的问题22…如下所示:
**Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.
For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.
What is the total of all the name scores in the file?**
下面是我为解决这个问题而编写的代码:
f = open("F:\gnames.txt", "r")
strr = f.read()
w = strr.replace('"', "")
li = w.split(',')
dic = {}
sum = 0
for ee in li:
for e in ee:
if (e == "A"):
sum+=1
elif (e == "B"):
sum+=2
elif (e == "C"):
sum+=3
elif (e == "D"):
sum+=4
elif (e == "E"):
sum+=5
elif (e == "F"):
sum+=6
elif (e == "G"):
sum+=7
elif (e == "H"):
sum+=8
elif (e == "I"):
sum+=9
elif (e == "J"):
sum+=10
elif (e == "K"):
sum+=11
elif (e == "L"):
sum+=12
elif (e == "M"):
sum+=13
elif (e == "N"):
sum+=14
elif (e == "O"):
sum+=15
elif (e == "P"):
sum+=16
elif (e == "Q"):
sum+=17
elif (e == "R"):
sum+=18
elif (e == "S"):
sum+=19
elif (e == "T"):
sum+=20
elif (e == "U"):
sum+=21
elif (e == "V"):
sum+=22
elif (e == "W"):
sum+=23
elif (e == "X"):
sum+=24
elif (e == "Y"):
sum+=25
else:
sum+=26
dic[ee] = sum
sum = 0
x = sorted(dic.items(), key=lambda t: t[1])
main_sum = 0
index = 0
for c in x:
t = c[1]*index
main_sum = main_sum + t
index+=1
print main_sum
实际答案是871198282。但是,我的代码给出的答案是995996966,与实际答案相比,这个数字是124798684。我的代码有什么问题?你知道吗
我认为你的问题在
x = sorted(dic.items(), key=lambda t: t[1])
线上。这将按分数而不是按名称的字母顺序对字典项进行排序。在lambda中将t[1]
更改为t[0]
,我怀疑您会得到更好的结果。你知道吗另一个可能的问题(有点模棱两可)是当你去加分数时你的索引。您将
index
从零开始,但是指令建议938的名称应该乘以938,而不是它基于零的索引,即937。您可能需要从index = 1
开始。你知道吗相关问题 更多 >
编程相关推荐