2017-02-01 48 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. 

再次感謝您對我的第一篇文章的輸入!