2017-02-01 47 views
1

我在Project Euler#6中遇到了问题。问题如下:python project euler 6 with any number

找到前100个自然数的平方和与平方和的差值。

我试图写我的代码,以欧拉(所有数字最高可达100)都可以代替你喜欢的任何数字(所有数字都包括x)。我决定为了做到这一点,你需要3个功能。代码是:

#the sumSquare function squares every number from 0 to number called 
#in the function and adds each term to a list. the function returns the sum 
#of all numbers in this list 

def sumSquare(num): 
    list1 = [] 

    for i in range(num+1): 
     x = i^2 
     list1.append(x) 
    return sum(list1) 


#the squareSum function adds every whole number from 0 up to and including 
#the number called in the function to list2. It returns the sum squared of #every number in the list 


def squareSum(num): 
    list2 = [] 
    for i in range(1,num+1): 
     list2.append(i) 
    return (sum(list2) * sum(list2)) 

def ans(num): 
    return squareSum(num) - sumSquare(num) 



print ans(100) 

我的输出为2549748,但我在网上正确的解决方案是25164150.有谁看到我错读。我只是在学习代码,所以我可能会错过某些更容易被更有经验的人发现的东西。但据我所知,这些清单在总结之前会被填入适当的数字。

+0

Unreleated但范围返回一个列表,所以不需要迭代并将值添加到第二个列表。总和(范围(1,num + 1))'将起作用。 – Alan

回答

2

i^2 

在Python中并不是一个正方形。正方形使用i*ii**2

0

您的代码是任何语言代码。但是sintax错误。 真的在Python中的权力是** 所以。

Python风格的代码看起来像一个:

print(sum(range(1, 101))**2 - sum([i**2 for i in range(1, 101)])) 

这就是为什么他们喜欢Python的(R)

0

感谢大家的输入。在思考了一下之后,我意识到这个代码是多么令人费解。我意识到,如果所有三个函数都采用相同的变量来解决问题,那么它可以简化为一个函数,负责独立处理每一步。想出了这个解决方案,它显然是更有效:

import time 


def ans(num): 
    numSq = [] 
    for i in range(1, num+1): 
     numSq.append(i**2) 
    return ((sum(range(1, num+1))**2)-sum(numSq)) 

start_time = time.time() 
print ans(100) 
print "This program took {} seconds to execute.".\ 
format(time.time() - start_time) 

运行程序您可以:

25164150 
This program took 0.00800013542175 seconds to execute. 

再次感谢您对我的第一篇文章的输入!