繁体   English   中英

有办法避免这种内存错误吗?

[英]Is there a way to avoid this memory error?

我目前正在研究Euler项目上的问题,到目前为止,我已经提出了解决此问题的代码。

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)

我试图通过禁用我无法从Google获得的垃圾收集来阻止垃圾收集,但无济于事。 我是否以错误的方式处理此问题? 在我的脑海中,这感觉是最自然的方式,而我对此感到茫然。

旁注:我使用的是PyPy 2.0 Beta2(Python 2.7.4),因为它比我使用的任何其他python实现都要快得多,而Scipy / Numpy却让我望而却步,因为我仍然才刚刚开始编程并我没有工程学或扎实的数学背景。

正如Kevin在评论中提到的那样,您的算法可能是错误的,但是无论如何您的代码都没有得到优化。

当使用非常大的列表时,通常使用generators ,有一个著名的,很棒的Stackoverflow答案解释了yieldgenerator的概念-Python 中的“ yield”关键字是做什么的?

问题是您的pairs = combinations(anums, 2)不会生成生成generator ,而是生成大对象,这会消耗更多的内存。

我将您的代码更改为具有此功能,因为您仅对集合进行了一次迭代,所以您可以延迟计算值:

def generator_sol(anums1, s):
      for comb in itertools.combinations(anums1, s):
        yield comb

现在,不是pairs = combinations(anums, 2) ,而是生成一个大对象。 使用:

pairs = generator_sol(anums, 2)

然后,代替使用lambda我将使用另一个generator

sums_sol = (x[0]+x[1] for x in pairs)

另一个技巧是,您最好看一下更合适的xrange ,它不会生成列表,而是会生成在许多情况下(例如此处)更有效的xrange object

让我建议您使用生成器 尝试更改此:

sums = map(lambda x: x[0]+x[1], pairs)

sums = (a+b for (a,b) in pairs)

Ofiris解决方案也可以,但是暗示itertools.combinations在错误时会返回一个列表。 如果您要继续解决项目欧拉问题,请查看itertools文档

问题是原子量很大-大约28000个元素长。 因此,对必须为28000 * 28000 * 8字节= 6GB。 如果使用numpy,则可以将anums转换为numpy.int16数组,在这种情况下,结果对将为1.5GB-更易于管理:

import numpy as np
#cast
anums = np.array([anums],dtype=np.int16)
#compute the sum of all the pairs via outer product
pairs = (anums + anums.T).ravel()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM