我目前正在通過項目歐拉的問題,到目前爲止我已經想出了這個問題的代碼。有沒有辦法避免這種內存錯誤?
from itertools import combinations
import time
def findanums(n):
l = []
for i in range(1, n + 1):
s = []
for j in range(1, i):
if i % j == 0:
s.append(j)
if sum(s) > i:
l.append(i)
return l
start = time.time() #start time
limit = 28123
anums = findanums(limit + 1) #abundant numbers (1..limit)
print "done finding abundants", time.time() - start
pairs = combinations(anums, 2)
print "done finding combinations", time.time() - start
sums = map(lambda x: x[0]+x[1], pairs)
print "done finding all possible sums", time.time() - start
print "start main loop"
answer = 0
for i in range(1,limit+1):
if i not in sums:
answer += i
print "ANSWER:",answer
當我運行這個我碰到一個MemoryError
。
回溯:
File "test.py", line 20, in <module>
sums = map(lambda x: x[0]+x[1], pairs)
我試圖阻止它從什麼我已經能夠從谷歌,但無濟於事得到禁止垃圾收集。我以錯誤的方式接近這個嗎?在我的腦海裏,這感覺就像是最自然的做法,而且我現在處於虧損狀態。
SIDE注意:我使用的是PyPy 2.0 Beta2(Python 2.7.4),因爲它比我用過的其他Python實現快得多,而且Scipy/Numpy在我頭上,因爲我仍然只是開始編程,我沒有工程或強大的數學背景。
你得到了多少內存?系統是64位的? – Ofiris
64位,8 GB的內存,雖然PyPy是32位的,如果這也有所改變。 –
你似乎有某個地方的錯誤。如果在'findanums'運行後'打印len(anums)',它會給出'28123',這意味着從1到28123的_every_數字是一個非常豐富的數字。我不認爲這是正確的。 – Kevin