1. 程式人生 > >python maximum recursion depth exceeded解決方式

python maximum recursion depth exceeded解決方式

用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_iter
    return fact_iter(num - 1, num*product)
  File "D:/python/spider/qq-music-spider/tt.py", line 12, in fact_iter
    return fact_iter(num - 1, num*product)
  File "D:/python/spider/qq-music-spider/tt.py", line 12, in fact_iter
    return fact_iter(num - 1, num*product)
  File "D:/python/spider/qq-music-spider/tt.py", line 12, in fact_iter
    return fact_iter(num - 1, num*product)
  File "D:/python/spider/qq-music-spider/tt.py", line 12, in fact_iter
    return fact_iter(num - 1, num*product)
  File "D:/python/spider/qq-music-spider/tt.py", line 12, in fact_iter
    return fact_iter(num - 1, num*product)
  File "D:/python/spider/qq-music-spider/tt.py", line 10, in fact_iter
    if num == 1:
RecursionError: maximum recursion depth exceeded in comparison

報錯提示超過最大遞迴深度。

該問題解決方式為加入如下指令碼:

import sys

sys.setrecursionlimit(1000000) #例如這裡設定為一百萬

執行:fact(1000),能正確出結果了。

但是,好像只可以執行到 fact(3930) 左右。

執行:fact(3930),報錯如下:

Process finished with exit code -1073741571 (0xC00000FD)

該問題可參考這篇博文,此處不再做具體討論: