Python:超出最大递归深度
我有以下递归代码,在每个节点调用 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
如果递归太深,当我调用递归函数时我应该会收到错误,但是当我打印字典时收到此错误。
I have the following recursion code, at each node I call sql query to get the nodes belong to the parent node.
here is the error:
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
Method that I call to get sql results:
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();
I actually don't have any issue with the above method but I put it anyways to give proper overview of the question.
Recursion Code:
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
Calling the recursive function
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();
Code to print the dictionary,
print "---Printing-------"
for key, value in baseCategoryTree.iteritems():
print key,
for elem in value[0]:
print elem + ',';
raw_input("Press Enter to continue...")
print
If the recursion is too deep I should be getting the error when I call my recursion function, but when I get this error when I print the dictionary.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以增加允许的堆栈深度 - 这样,就可以进行更深的递归调用,如下所示:
...但我建议您首先尝试优化代码,例如使用迭代而不是递归。
You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:
... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.