我有一个递归调用的函数。当我运行它时,出现错误 “调用 Python 对象时超出了最大递归深度”
如何增加 mac 的限制?如果我使用以下内容,我会收到错误消息“无法增加 mac 的限制”
resource.setrlimit(resource.RLIMIT_STACK, (2**24,-1))
sys.setrecursionlimit(10**6)
最佳答案
我遇到了一个问题,我有可能重复数十亿次,而我这样做的方法是扁平化递归。不知道这个方法以前有没有记载,因为是自己想出来的,不是自己找的。您真正需要做的就是将每个函数的局部命名空间放入一个列表中。如果没有解决方法,这将需要更改您的实际代码。这是它的工作原理:
假设我有这个功能:
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
现在,这在传统上是递归的。为了使其适用于没有限制的任何嵌套,我会这样做:
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
两个字:脑洞大开
我写的函数工作正常,但是没有优化。如果你想要速度,首先要确保你理解这个函数,然后结合索引溢出的检查,方法是将“x”和“y”代码块多态化。
您将不得不根据您的代码调整它,但只要您理解它,它应该不会太大或成为问题。另外,答案是跨平台且不受限制。
关于Python - 增加 mac osx 中的递归限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36069059/