Python:超出最大递归深度

问题描述 投票:81回答:2

我有以下递归代码,在每个节点上我都调用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

我调用以获取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();

我实际上对上述方法没有任何问题,但是无论如何我都给出了适当的问题概述。

递归代码:

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

调用递归函数

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();

打印字典的代码,

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

如果递归太深,则在调用递归函数时会出现错误,但是在打印字典时出现此错误。

python recursion max depth tree-traversal
2个回答
158
投票

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

import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values

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


0
投票

tkinter中的织补代码正在自我调用...帮助!

文件“ /usr/lib/python3.6/tkinter/init.py”,第2098行,在getattr中返回getattr(self.tk,attr)

© www.soinside.com 2019 - 2024. All rights reserved.