22-python基礎11-遞迴函式

來源:互聯網
上載者:User

標籤:img   一個   logs   sys   執行個體   class   簡單   斐波那契數列   port   

遞迴

1.定義:在函數內部,可以調用其他函數。如果一個函數在內部調用自身本身,這個函數就是遞迴函式。

階乘執行個體

1 n = int(input(">>:"))2 3 4 def f(n):5     s = 16     for i in range(2, (n + 1)):7         s *= i8     return s9 print(f(n))

遞迴

1 def factorial_new(n):2  3     if n==1:4         return 15     return n*factorial_new(n-1)6  7 print(factorial_new(3))

遞迴函式的特點:

  1 調用自身函數

  2 有一個明顯的結束條件,問題規模相比上次遞迴有所減少

優點: 定義簡單,邏輯清晰,所有的遞迴函式都可以寫成迴圈的方式,但是迴圈的邏輯不如遞迴清晰。

但是,遞迴的效率不高,遞迴層次過多會導致棧溢出,大概1000層。

2.斐波那契數列
 1 def fibNum(n):          #斐波那契數列 2     a, b = 0, 1 3     for i in range(n): 4         b, a = a+b, b 5     return b 6 n = int(input(">>:")) 7 if n == 1: 8     print(0) 9 elif n == 2:10     print(1)11 else:12     print(fibNum(n-2))

用遞迴寫

 1 def fibo(n): 2     before = 0 3     after = 1 4     if n == 0 or n == 1: 5         return n 6  7     if n <= 3: 8         return 1 9     return fibo(n-1)+fibo(n-2)10 11 print(fibo(3))

遞迴效率低,當數字過大時,會很慢

3.python遞迴的限制

 
import sys
print(sys.getrecursionlimit())
#1000
sys.setrecursionlimit(10000)
print(sys.getrecursionlimit())
#10000

 

22-python基礎11-遞迴函式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.