【问题标题】:Python - Increase recursion limit in mac osxPython - 在 mac osx 中增加递归限制
【发布时间】:2016-07-04 07:16:49
【问题描述】:

我有一个递归调用的函数。当我运行它时,我收到错误“调用 Python 对象时超出最大递归深度”

如何增加mac上的限制?如果我使用以下内容,我会收到错误 "cannot increase the limit on mac"

resource.setrlimit(resource.RLIMIT_STACK, (2**24,-1))
sys.setrecursionlimit(10**6)

【问题讨论】:

  • 这可能是Python limitation,与 Mac 无关。
  • 您是否考虑过重写递归以实现对数堆栈增长而不是线性堆栈增长的可能性?例如,可以通过将到目前为止的最大值与列表其余部分的最大值进行比较来递归地设置列表的最大值,但堆栈将随着列表的大小线性增长。更好的解决方案是找到列表前半部分和列表后半部分的最大值,并取两者中较大的一个,这不会减少工作量,但会以列表大小的对数方式增长堆栈.也许您的问题可以类似地重铸。
  • 有趣的@pjs,你有这样的例子吗?
  • 我正在寻找答案,但它真的很长,等待......
  • @Goodies Yes, I do。但是如果没有看到代码,就不可能说同样的方法是否适用于 nbrugir。

标签: python macos python-3.x recursion


【解决方案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'代码块进行多态化来结合索引溢出检查。

您必须根据您的代码调整它,但只要您理解它,它应该不会有太大问题或问题。另外,答案是跨平台且不受限制。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-13
    • 1970-01-01
    • 1970-01-01
    • 2019-06-23
    • 2013-05-31
    • 2022-01-21
    • 2015-03-23
    • 2016-02-18
    相关资源
    最近更新 更多