【发布时间】:2013-12-12 07:36:32
【问题描述】:
当此代码运行时,OSX 会通知我应用程序内存不足并暂停应用程序。 Python 使用的空间量很快就突破了 10 个演出。此代码从未达到 Python 的最大递归级别,它应该只达到 525 最坏情况,但由于缓存它应该小得多。我有一种感觉,每个级别的递归都会复制列表链,但它似乎是一个全局变量,应该与 collatz() 的每次调用共享。我在 stackoverflow 上寻找过类似的问题,但我没有发现任何相同的问题。
# The following iterative sequence is defined for the set of positive integers:
# n = n/2 (n is even)
# = 3n+1 (n is odd)
# Using the rule above and starting with 13, we generate the following sequence:
# 13,40,20,10,5,16,8,4,2,1
# It can be seen that this sequence (starting at 13 and finishing at 1) contains 10
# terms. Although it has not been proved yet (Collatz Problem), it is thought that
# all starting numbers finish at 1.
# Which starting number, under one million, produces the longest chain?
# Comments: I'm using dynamic programming to avoid computing the same values over and over
# again.
lim = 1000000
chain = [1,1]
maxL = 0
def collatz(i):
if i >= len(chain): chain.extend([None]*(i-len(chain)+1))
if chain[i] == None: chain[i] = 1 + collatz(i/2 if i%2==0 else 3*i+1)
return chain[i]
for i in range(1, lim):
maxL = i if (collatz(i) > chain[maxL]) else maxL
print i, chain[maxL]
print "collatz chain of {} is {} terms long.".format(maxL, collatz(maxL))
编辑:在这里查看我的工作字典实现:https://stackoverflow.com/a/20229855/1084773。
【问题讨论】:
-
我编辑了我的答案,在最后一段中我解释了你的记忆问题来自哪里。
-
我希望与 Euler 项目问题相关的问题和代码实际上与问题演示和讨论相关联(并对这些术语进行搜索友好的引用,例如在这种情况下为“Hailstone”):projecteuler.net/index.php?section=problems&id=14 blog.functionalfun.net/2008/07/…
标签: python memory recursion out-of-memory