Python递归长度太长?

Python递归长度太长?,python,recursion,Python,Recursion,我正在处理一个checkio.org问题,我构建了一个使用递归的解决方案,除非在第8次测试中运行,否则我会遇到以下错误: RuntimeError: maximum recursion depth exceeded while calling a Python object, count_gold, 16, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29,

我正在处理一个checkio.org问题,我构建了一个使用递归的解决方案,除非在第8次测试中运行,否则我会遇到以下错误:

RuntimeError: maximum recursion depth exceeded while calling a Python object, count_gold, 16, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29,
我截断了结尾,但它持续了很长时间。我认为这是我对递归工作方式的一个基本误解。起初,我很不愿意发布我的代码,因为我不想给出答案,但我认为如果我不将问题联系起来,那么我的代码就会变得模糊不清。现在我们开始:

def mystery_function(pyramid, perm=0, lastmax=0, result = [], running=False):

    if not running:
        result = []

    bitstr = bin(perm).zfill(len(pyramid)+1)
    bitstr = bitstr.replace("b","")

    j, newmax = 0, 0

    for i in range(len(pyramid)):

        j += int(bitstr[i])
        newmax += pyramid[i][j]

    maxpermute = "1"*(len(pyramid))
    result.append(newmax)

    if newmax < lastmax:
        nextmax = lastmax
    else:
        nextmax = newmax

    if perm < int(maxpermute,2):
        mystery_function(pyramid, perm+1, nextmax, result, True)

    return max(result)
def神秘函数(金字塔,perm=0,lastmax=0,result=[],running=False):
如果未运行:
结果=[]
bitstr=bin(perm).zfill(len(棱锥)+1)
bitstr=bitstr.replace(“b”,“”)
j、 newmax=0,0
对于范围内的i(len(金字塔)):
j+=int(比特串[i])
newmax+=金字塔[i][j]
maxpermute=“1”*(透镜(金字塔))
result.append(newmax)
如果newmax
就像我说的,我认为问题在于我只是不完全理解递归。我读了这篇文章:但它似乎不适用,因为我的递归将分解为基本情况并停止

有什么想法吗?对于那些感兴趣的人(并且根据我的函数了解问题),递归在测试8中失败

注意:在函数中,“金字塔”是长度在1到20个元组之间的元组。我们应该通过“金字塔”找到产生最大总和的路径,并返回该总和

尝试以下方法:

import sys
sys.setrecursionlimit(5000)

Python的限制是1000,我相信这只是一个关于递归的简要说明:完全有可能超过最大递归深度,即使您的代码最终会达到基本情况。毕竟,计算机内存是有限的。如果你开始使用递归,首先解决问题的一小部分通常会有帮助。。。比如说,你的树/金字塔的前两三层。如果你想找到最大的一笔钱,可能没有办法避免走遍整棵树。因此,不必担心边检查边检查,只需构建一个显示每个可能路径总和的解决方案即可。首先分解问题,然后进行优化。我不认为这是问题所在,但要非常小心地创建一个默认参数为
[]
的函数,这是新python程序员的常见问题:@Apc0243,最大递归深度约为1000。由2^20个元素组成的字节数组只是1个MiB,对于现代RAM来说绝对不是问题。(当然,Python对象列表会占用更多内存,但考虑简单数组是一个有用的基准)。@DavidCain ok,那么通过循环运行这个可能会更好,嗯。我只是用一个循环来测试它,它更简单,而且可以工作!谢谢你,大卫!