2011-11-18 131 views
69

我有以下递归代码,在每个节点我调用sql查询来获取节点属于父节点。Python:超过最大递归深度

这里是错误:

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

我居然没有上述方法的任何问题,但我把它给反正:

,我打电话让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 

方法给出适当的问题概述。

递归代码:

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 

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

+7

迭代而不是递归地重写它。 –

+1

'首先:'检查对于elem来说是多余的:'。如果查询返回一个空的结果列表,那么迭代它将简单地,正确地做任何事情,如你所愿。此外,你可以创建列表更简单的清单理解(和那些分号是不必要的,通常被认为是丑陋:)) –

+0

@KarlKnechtel对不起,关于分号,你能告诉我只是进入Python编程.... :) –

回答

139

您可以增加允许的堆栈深度 - 这一点,更深层次的递归调用将成为可能,这样的:

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

...但我建议你先尝试优化你的代码,实例,使用迭代而不是递归。

+0

我得到错误,当我尝试打印,如果递归太深我应该得到错误当我调用递归函数时。因为下线我调用这个函数,并将结果保存在字典中,当我尝试打印字典时,我得到这个错误。我已经更新了代码。 –

+0

我添加了行而不是10000我添加了30000,但我结束了分段错误(核心转储):( –

+4

尝试一个较小的数字,然后 –

相关问题