Python:超出了最大递归深度

add*_*ons 79 python recursion max tree-traversal depth

我有以下递归代码,在每个节点我调用sql查询以获取属于父节点的节点.

这是错误:

Exception RuntimeError: 'maximum recursion depth exceeded' in <bound method DictCursor.__del__ of <MySQLdb.cursors.DictCursor object at 0x879768c>> ignored

RuntimeError: maximum recursion depth exceeded while calling a Python object
Exception AttributeError: "'DictCursor' object has no attribute 'connection'" in <bound method DictCursor.__del__ of <MySQLdb.cursors.DictCursor object at 0x879776c>> ignored
Run Code Online (Sandbox Code Playgroud)

我调用以获取sql结果的方法:

def returnCategoryQuery(query, variables={}):
    cursor = db.cursor(cursors.DictCursor);
    catResults = [];
    try:
        cursor.execute(query, variables);
        for categoryRow in cursor.fetchall():
            catResults.append(categoryRow['cl_to']);
        return catResults;
    except Exception, e:
        traceback.print_exc();
Run Code Online (Sandbox Code Playgroud)

我实际上对上述方法没有任何问题,但我还是把它放在了正确的问题概述上.

递归代码:

def leaves(first, path=[]):
    if first:
        for elem in first:
            if elem.lower() != 'someString'.lower():
                if elem not in path:
                    queryVariable = {'title': elem}
                    for sublist in leaves(returnCategoryQuery(categoryQuery, variables=queryVariable)):
                        path.append(sublist)
                        yield sublist
                    yield elem
Run Code Online (Sandbox Code Playgroud)

调用递归函数

for key, value in idTitleDictionary.iteritems():
    for startCategory in value[0]:
        print startCategory + " ==== Start Category";
        categoryResults = [];
        try:
            categoryRow = "";
            baseCategoryTree[startCategory] = [];
            #print categoryQuery % {'title': startCategory};
            cursor.execute(categoryQuery, {'title': startCategory});
            done = False;
            while not done:
                categoryRow = cursor.fetchone();
                if not categoryRow:
                    done = True;
                    continue;
                rowValue = categoryRow['cl_to'];
                categoryResults.append(rowValue);
        except Exception, e:
            traceback.print_exc();
        try:
            print "Printing depth " + str(depth);
            baseCategoryTree[startCategory].append(leaves(categoryResults))
        except Exception, e:
            traceback.print_exc();
Run Code Online (Sandbox Code Playgroud)

打印字典的代码,

print "---Printing-------"
for key, value in baseCategoryTree.iteritems():
    print key,
    for elem in value[0]:
        print elem + ',';
    raw_input("Press Enter to continue...")
    print
Run Code Online (Sandbox Code Playgroud)

如果递归太深,我应该在调用递归函数时收到错误,但是当我打印字典时出现此错误.

Ósc*_*pez 156

您可以增加允许的堆栈深度 - 这样,可以进行更深层次的递归调用,如下所示:

import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values
Run Code Online (Sandbox Code Playgroud)

...但我建议您首先尝试优化代码,例如,使用迭代而不是递归.

  • 有一个原因,它设置为1000 ...我相信[Guido van Rossum说了一些关于这一点](http://neopythonic.blogspot.com/2009/04/tail-recursion-elimination.html). (14认同)
  • 然后尝试一个较小的数字 (4认同)
  • 所以Guido的论点是正确的尾调用(1)提供了更糟糕的堆栈跟踪 - 而不是在迭代编写时没有帧?怎么会更糟?(2)如果我们给他们一些好的东西,他们可能会开始依赖它.(3)我不相信它,它闻起来像Scheme.(4)Python的设计很糟糕,因此编译器无法有效地发现是否有尾调用.我猜我们可以达成一致意见吗? (3认同)
  • @hajef 第三,尾调用当然不仅仅适用于列表;任何树结构获胜。尝试在没有递归调用的情况下遍历一棵树;您最终会手动对堆栈进行建模。最后,您关于 Python 从未以这种方式设计过的论点当然是正确的,但并不能让我相信它是上帝般的设计。 (2认同)
  • 仅仅因为 van Rossum 在他的帽子里有一只关于递归的蜜蜂并不意味着递归而不是迭代不是“最佳”:取决于你正在优化什么! (2认同)