由于堆栈溢出,需要使此递归算法迭代



基本上我在Python中有这个巨大的函数(我已经简化了基本功能)

def rec(a,b):
  if stoppingCondition==True: return 1
  key=(a,b)
  if key in memo: return memo[key]
  if b==side condition:
       memo[key]=rec(a+1,b)   #RECURSIVE CALL
       return memo[key]
  total=0
  for d in D:
      if condition1==True:
          b=some process 1
          total+=rec(a+1,b)   #RECURSIVE CALL
      elif condition2==True:
          for x,y in d:
              if (some break condition==True): break
          else: #only gets called if break didnt happen
              b=some process 2
              total+=rec(a+1,b)   #RECURSIVE CALL
   memo[key]=total
   return memo[key]

而且我花了很多时间让它迭代,因为它会爆炸到更深的递归级别。我已经阅读了有关转换为循环和堆栈之类的其他线程,但我无法使其正常工作。

你总是可以计算所有brec(a, b),从最高a开始,在一个简单的循环中递减,没有递归。现在,如果对rec()的所有可能调用的遍历很少,则此解决方案不可行,因为它会引入许多不必要的计算。

另一种解决方案是尝试在 Python 中实现尾调用优化。我还没有尝试过,但你可能想测试这个装饰器。

一个不太优雅的解决方案是增加递归限制以满足您的需求:

import sys
sys.setrecursionlimit(10000)

最新更新