我有一个递归调用的函数。当我运行它时,我得到错误"在调用Python对象时超出了最大递归深度"
如何增加mac的限制?如果我使用以下内容,则会收到错误"无法增加对mac的限制"
resource.setrlimit(resource.RLIMIT_STACK, (2**24,-1))
sys.setrecursionlimit(10**6)
答案 0 :(得分:1)
我有一个问题,我有可能重复几十亿次,而我这样做的方式是展平递归。我不知道之前是否记录过这种方法,因为我自己想出来而不是找到它。您真正需要做的就是将每个函数的本地命名空间放在一个列表中。如果没有解决方法,这将需要更改您的实际代码。以下是它的工作原理:
说我有这个功能:
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'代码块来对它们进行多态化。
您必须对此代码进行调整,但只要您了解它,它就不应该太多或者是问题。此外,答案是跨平台和无限制。