在學習漢娜塔的時候,遇到一個error RecursionError: maximum recursion depth exceeded in comparison
經過百度,百度的方法:
加上:
import sys
sys.setrecursionlimit(100000)
可是我加上之后結果如下,並沒有解決問題,python還提示意外退出:
1、再此經過思考(也不是思考,再從頭看了學習視頻,添加了兩個return None,問題解決✌️✌️💕)
python 函數要么返回預期的值,要么返回None
2、注意點,遞歸要有結束的條件:如下
1 def fun_a(n): 2 #print(n) 3 #if n == 1: 4 #return 1 5 return n*fun_a(n-1) 6 rst=fun_a(5) 7 print(rst)
Traceback (most recent call last): File "/Users/fudandan/Desktop/hello/11/diaoyong.py", line 6, in <module> rst=fun_a(5) File "/Users/fudandan/Desktop/hello/11/diaoyong.py", line 5, in fun_a return n*fun_a(n-1) File "/Users/fudandan/Desktop/hello/11/diaoyong.py", line 5, in fun_a return n*fun_a(n-1) File "/Users/fudandan/Desktop/hello/11/diaoyong.py", line 5, in fun_a return n*fun_a(n-1) [Previous line repeated 996 more times] RecursionError: maximum recursion depth exceeded [Finished in 0.1s with exit code 1]
結束條件加上:
1 def fun_a(n): 2 #print(n) 3 if n == 1: 4 return 1 5 return n*fun_a(n-1) 6 rst=fun_a(5) 7 print(rst)
就可以自行並且沒有錯誤了
每天進步一點點~~