用Python写了一个递归脚本,脚本如下
def fact(n): return fact_iter(n, 1) def fact_iter(num, product): if num == 1: return product return fact_iter(num - 1, num*product)
执行:fact(1000)
报错如下:
File "D:/python/spider/qq-music-spider/tt.py", line 12, in fact_iterreturn fact_iter(num - 1, num*product)File "D:/python/spider/qq-music-spider/tt.py", line 12, in fact_iterreturn fact_iter(num - 1, num*product)File "D:/python/spider/qq-music-spider/tt.py", line 12, in fact_iterreturn fact_iter(num - 1, num*product)File "D:/python/spider/qq-music-spider/tt.py", line 12, in fact_iterreturn fact_iter(num - 1, num*product)File "D:/python/spider/qq-music-spider/tt.py", line 12, in fact_iterreturn fact_iter(num - 1, num*product)File "D:/python/spider/qq-music-spider/tt.py", line 12, in fact_iterreturn fact_iter(num - 1, num*product)File "D:/python/spider/qq-music-spider/tt.py", line 10, in fact_iterif num == 1:RecursionError: maximum recursion depth exceeded in comparison
报错提示超过最大递归深度。
该问题解决方式为加入如下脚本:
import sys sys.setrecursionlimit(1000000) #例如这里设置为一百万
执行:fact(1000),能正确出结果了。