You are here
Home > python

RuntimeError: maximum recursion depth exceeded in comparison

python 递归,过深的调用会导致栈溢出:

Python 3.5 中默认的最大递归深度是998,当尝试递归第990时便出现递归深度超限的错误:

RuntimeError: maximum recursion depth exceeded in comparison

(ipython中是2982)

---------------------------------------------------------------------------
RecursionError                            Traceback (most recent call last)
<ipython-input-68-d553d99b0e53> in <module>
      4     return n * fact(n - 1)
      5
----> 6 fact(2983)

<ipython-input-68-d553d99b0e53> in fact(n)
      2     if n == 1:
      3         return 1
----> 4     return n * fact(n - 1)
      5
      6 fact(2983)

... last 1 frames repeated, from the frame below ...

<ipython-input-68-d553d99b0e53> in fact(n)
      2     if n == 1:
      3         return 1
----> 4     return n * fact(n - 1)
      5
      6 fact(2983)

RecursionError: maximum recursion depth exceeded in comparison

可以在文件初始位置修改这个最大递归次数,如下:

import sys
sys.setrecursionlimit(10000)  # set the maximum depth as 10000

sys.setrecursionlimit() 只是修改解释器在解释时允许的最大递归次数,此外,限制最大递归次数的还和操作系统有关,经过测试:
windows下最大迭代次数约4400次,linux下最大迭代次数约为24900次(python 2.7 64位)

发表评论

Top