python 停留在项目Euler #13上

vcirk6k6  于 2022-12-21  发布在  Python
关注(0)|答案(7)|浏览(124)

请帮助我理解为什么我解决13th Project Euler problem的Python代码是不正确的,我相信我正确地理解了任务,我认为我的代码是正确的,但显然不是。

number = '5000 digit number - see in the problem decription at the provided link'
list1 = [number[i:i+100] for i in range(0, len(number), 100)]
temp = []
for i in range(0, len(list1)):
    y = int(list1[i])
    temp.append(y)
print sum(temp)
cxfofazt

cxfofazt1#

首先,数字长度为50位,而不是100位。请更改以下内容:

list1 = [number[i:i+100] for i in range(0,len(number),100)]

对此:

list1 = [number[i:i+50] for i in range(0,len(number),50)]

第二,您打印的是整个总和,而不是前十位数字。

print str(sum(temp))[:10]
n7taea2i

n7taea2i2#

简单得多:

s = 'copied and pasted from the page'

result = sum(map(int, s.splitlines()))[:10]
odopli94

odopli943#

只需要对前11个数字求和,

somme11=sum(int(number2[i:i+11]) for i in range(100))
print(somme11)
print( 'the ten first digits are' , somme11//1000)

因为进位不能超过99。

4893024188690
the ten first digits are 4893024188
zqry0prt

zqry0prt4#

使用StringIO将number作为输入字符串,并通过将每个元素转换为整数值来迭代元素

from io import StringIO

number = StringIO(""" # Paste one-hundred 50 numbers """) 

print(str(sum(map(lambda x: int(x), number)))[:10])
>>> '5537376230'
9o685dep

9o685dep5#

另一种方法是将数字加载到文件中,然后将它们相加,除非我也完全误解了这个问题。

with open("sum.nums","r") as f:
    data = f.readlines()
total = 0
for i in data:
    total += int(i)
print "1st 10 digits ", str(total)[:10], "of total", total

前10位数字5537376230,总计5537376230390876637302048746832985971773659831892672

emeijp43

emeijp436#

其实很简单

def e13():
    f=open("100x50digits.txt")
    summ=0
    for line in f:
        summ+=int(line[:11])
    print(int(summ/1000))
    f.close()
e13()
laik7k3q

laik7k3q7#

number = '''The 100 lines of 50 characters'''

numbers = number.splitlines()          #Devide the string into a list of strings.
numbers = [int(i) for i in numbers]    #Convert all elements into integers.
totalSum = str(sum(numbers))           #Add everything and convert to a string.
print(totalSum[:10])                   #Print the first 10 digits of the result.

正确答案是5537376230,请与体育部核对。
这里真实的的挑战是处理一个很长的字符串

相关问题