坚持项目欧拉#13

时间:2015-10-13 16:22:55

标签: python

请帮助我理解为什么解决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)

5 个答案:

答案 0 :(得分:1)

首先,这些数字是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]

答案 1 :(得分:1)

更简单:

s = 'copied and pasted from the page'

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

答案 2 :(得分:0)

只需要将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

答案 3 :(得分:0)

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

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

答案 4 :(得分:0)

很简单

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