因子递归方法Python的运行时错误

时间:2016-06-03 15:43:31

标签: python-3.x runtime-error factorial

def recursive_factorial(n):
   if n == 1: #base case
       return 1
   else:  
       return n * recursive_factorial(n-1) #recursive call

请帮助我收到运行时错误:RuntimeError('超出最大递归深度'

1 个答案:

答案 0 :(得分:1)

因此,您已达到递归限制。这可以通过导入sys和设置来重置,但是:

Seriously don't use setrecursionlimit

在使用递归之前,你肯定会尝试迭代。请尝试这个,如果你不能设置递归限制,这应该有效:

re(n):
  g=n
  while n>1:
    g*=(n-1)
    n-=1
  return g

如果您确实想要设置递归限制,请确保仅暂时执行此操作。否则,如果过于递归,其他更重的函数可能会产生问题:

import sys
def thing_i_want_to_recurse(n)
  c_limit = sys.getrecursionlimit()
  sys.setrecurionlimit(n)
  yield
  sys.setrecurionlimit(c_limit)

再次迭代是最好的:

 [in]: sys.setrecursionlimit(3)
 [in]: recursive_factorial(5)
 [out]:Error: maximum recusion depth exceeded
 [in]: re(5) #no problem
 [out]: 120