如何解决这个内存错误 - python
我有以下代码
def gen_primes():
D = {}
q = 2
while True:
if q not in D:
yield q
D[q * q] = [q]
else:
for p in D[q]:
D.setdefault(p + q, []).append(p)
del D[q]
q += 1
f = open("primes1.txt","w")
filen = 1
ran1 = 1
ran2 = 10000000
k = 1
for i in gen_primes():
if (k >= ran1) and (k <= ran2):
f.write(str(i) + "\n")
if k%1000000 == 0:
print k
k = k + 1
else:
ran1 = ran2 + 1
ran2 = ran2 + 10000000
f.close()
filen = filen + 1;
f = open("primes" + str(filen) + ".txt","w")
if k > 100000000:
break
f.close()
素数生成算法取自 Python 中的简单素数生成器
这程序出现内存错误
Traceback (most recent call last):
File "C:\Python25\Projects\test.py", line 43, in <module>
for i in gen_primes():
File "C:\Python25\Projects\test.py", line 30, in gen_primes
D.setdefault(p + q, []).append(p)
MemoryError
我试图在一个文件中存储连续的 10,000,000 个素数。
I have the following code
def gen_primes():
D = {}
q = 2
while True:
if q not in D:
yield q
D[q * q] = [q]
else:
for p in D[q]:
D.setdefault(p + q, []).append(p)
del D[q]
q += 1
f = open("primes1.txt","w")
filen = 1
ran1 = 1
ran2 = 10000000
k = 1
for i in gen_primes():
if (k >= ran1) and (k <= ran2):
f.write(str(i) + "\n")
if k%1000000 == 0:
print k
k = k + 1
else:
ran1 = ran2 + 1
ran2 = ran2 + 10000000
f.close()
filen = filen + 1;
f = open("primes" + str(filen) + ".txt","w")
if k > 100000000:
break
f.close()
The prime generation algorithm is taken from Simple Prime Generator in Python
This program is giving memory error
Traceback (most recent call last):
File "C:\Python25\Projects\test.py", line 43, in <module>
for i in gen_primes():
File "C:\Python25\Projects\test.py", line 30, in gen_primes
D.setdefault(p + q, []).append(p)
MemoryError
I am trying to store consecutive 10,000,000 primes in one file.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这个素数生成器不使用太多内存。它也不是很快。
This prime generator doesn't use very much memory. It's also not very fast.
尝试使用此生成器: http://code.activestate .com/recipes/366178-a-fast-prime-number-list-generator/
速度快得令人难以置信(几秒钟内 10000000 个素数),而且
保存起来 并不消耗内存在文件中,也许简单地执行以下操作会更容易:
Try using this generator: http://code.activestate.com/recipes/366178-a-fast-prime-number-list-generator/
Is incredibly fast (10000000 primes in a couple of seconds) and not that memory consuming
to save in a file perhaps it's easier simply to do something like:
我在我的机器上运行了稍微修改过的代码 10^6 primes in ~30 sec (我正在运行 Python 3.2)
这是代码:
I've run slightly modified code on my machine 10^6 primes in ~30 sec (I am running Python 3.2)
Here is the code:
安装包 gmpy ,您就可以编写文件而无需太多内存
Install the package gmpy and you can write the file without requiring much memory at all