nab*_*gir 7 python macos recursion python-3.x
我有一个递归调用的函数.当我运行它时,我得到错误"调用Python对象时超出了最大递归深度"
如何增加mac的限制?如果我使用以下,我得到错误"不能增加对mac的限制"
resource.setrlimit(resource.RLIMIT_STACK, (2**24,-1))
sys.setrecursionlimit(10**6)
Run Code Online (Sandbox Code Playgroud)
我遇到了一个问题,我有可能重复数十亿次,而我的方法是展平递归。我不知道这个方法以前是否有文档记录,因为我自己想出了它,而不是找到它。您真正需要做的就是将每个函数的本地命名空间放入列表中。如果没有解决方法,这将需要更改您的实际代码。它的工作原理如下:
假设我有这个功能:
def flatten_a_list(obj):#[[6,5],7,[3,[9,0]]] -> [6,5,7,3,9,0]
flattened = []
for item in obj:
if type(item) == list:
flattened.append(flatten_a_list(item))
else:
flattened.append(item)
return flattened
Run Code Online (Sandbox Code Playgroud)
现在,这在传统上是递归的。为了使其能够无限制地适用于任意数量的嵌套,我会这样做:
from copy import deepcopy
def improved(obj):#[[6,5],7,[3,[9,0]]] -> [6,5,7,3,9,0]
flattened = []
position = [0]
while True:
print('position: {}'.format(str(position)))
x = deepcopy(obj)
try:
for index in position:
x = x[index]
except (IndexError, TypeError):
break
if type(x) == list:
position.append(0)
print('continuing')
continue
else:
flattened.append(x)
#Test the next position
test = deepcopy(position)
test[-1] += 1
x = deepcopy(test)
print('x: {}'.format(x))
try:
y = deepcopy(obj)
for index in x:
y = y[index]
position = deepcopy(test)
except (IndexError, TypeError):
position = position[:-1]
try:
position[-1] += 1
except IndexError:
break
return flattened
Run Code Online (Sandbox Code Playgroud)
两个字:心灵扭曲
我写的函数运行良好,但尚未优化。如果您想要速度,首先确保您理解该函数,然后通过对“x”和“y”代码块进行多态化来结合索引溢出检查。
您必须使其适应您的代码,但只要您理解它,它就不应该有太大问题。另外,答案是跨平台且不受限制。