gpt4 book ai didi

python - Project Euler #22 Python,缺少 2205 个点?

转载 作者:行者123 更新时间:2023-11-28 23:01:50 26 4
gpt4 key购买 nike

我正在研究欧拉计划的第 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?

http://projecteuler.net/problem=22

当我编译下面的代码时,我得到了答案 871196077。正确答案应该是871198282

import time

def euler_22():

## Creates a sorted list of the names in Py_Euler_22.txt
names = open('Py_Euler_22.txt', 'r')
names = names.read()
names = names.split('","')
names[0] = names[0][1:]
names[-1] = names[-1][:-2]
names = sorted(names)

## Creates a dictionary: letter -> value
value_letters = {}
start = ord("A")
for i in range(0, 26):
value_letters[chr(start+i)] = i+1

result = 0

for i in range(1, len(names)+1):
name = names[i-1]
sum_letters = 0
for letter in name:
sum_letters += value_letters[letter]*i
# = value of the letter multiplied with the name position
result += sum_letters
return result

tstart = time.time() print euler_22() print "Run time: " + str(time.time() - tstart)

我试图找到一个具有类似解决方案的程序,但我只知道 Python,这限制了选项。我用我创建的更简单的文本文件运行了这个程序,我可以在没有程序的情况下得到答案,而且所有这些都有效。我用谷歌搜索了问题的答案,但这也无济于事,因为我找不到遗漏的地方。

我是初学者,所以我非常感谢有关程序和 Python 的任何提示,而不仅仅是那些可以帮助我正确解决问题的提示。

非常感谢!

最佳答案

你不小心弄错了一个名字。

这里 qnames 是你的代码生成的名称的排序列表,sorted_names 是我的:

>>> for a,b in zip(qnames, sorted_names):
... if a != b:
... print a, b
...
ALONS ALONSO

为了好玩:一行 - 嵌套列表理解,avast ye!

print sum ( [ (pos+1) * nv for pos, nv in enumerate([ sum ( [ ord(char) - 64 for char in name ] ) for name in sorted([name.strip('"') for name in open('names.txt','r').readline().split(",")]) ]) ] )

或者更易读:

print sum (
[(pos+1) * nv for pos, nv in
enumerate([ sum ([ ord(char) - 64 for char in name ] ) for name in
sorted([name.strip('"') for name in
open('names.txt','r').readline().split(",")]) ]) ] )

黑魔法是 ASCII A 是整数 65,ASCII B 是整数 66,等等on - 所以 ord(char) - 64 为您提供 char 的“字母值”。


编辑 2:

为了您的娱乐,我将完整的、人类可读的解决方案塞进了一行。

with open('names.txt','r') as f:
data = f.readline();

names = [name.strip('"') for name in data.split(",")]
sorted_names = sorted(names)
name_values = [ sum ( [ ord(char) - 64 for char in name ] ) for name in sorted_names ]
name_position_values = [ (pos+1) * nv for pos, nv in enumerate(name_values) ]
total_sum = sum(name_position_values)

# debug output
from pprint import pprint
#position, word value, position * word value, word
pprint(zip(xrange(1,len(names)+1),name_values,name_position_values,sorted_names))

请注意大量使用列表理解 [x for x in list_of_xes] 而不是循环,以及 sum() 函数而不是 for x in xes : 总和 += x

这里还有一些其他技巧,但带回家的教训是列表理解和处理列表的函数可以使您的代码更简单、更易于阅读。


编辑 3:

pprint.pprint() 函数是一个“漂亮的print()”。它非常适合调试。


编辑 4:

代码高尔夫版本(142 个字符):

print sum([(p+1)*v for p,v in enumerate([sum(map(ord,n))-64*len(n) for n in sorted([n[1:-1] for n in open('names.txt').read().split(",")])])])

关于python - Project Euler #22 Python,缺少 2205 个点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10493702/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com