(一)Python入門-5函數:08遞歸函數
阿新 • • 發佈:2019-05-12
lse *** 返回 n) 內存 bubuko 圖片 bsp 部分
遞歸函數:
遞歸函數指的是:自己調用自己的函數,在函數體內部直接或間接的自己調用自己。遞歸類 似於大家中學數學學習過的“數學歸納法”。
每個遞歸函數必須包含兩個部分:
1. 終止條件 表示遞歸什麽時候結束。一般用於返回值,不再調用自己。
2. 遞歸步驟 把第 n步的值和第 n-1步相關聯。
遞歸函數由於會創建大量的函數對象、過量的消耗內存和運算能力。在處理大量數據時,謹 慎使用。
【操作】測試遞歸函數基本原理
#測試遞歸函數基本原理 def test01(n): print("test01:",n) ifn == 0: print(‘over‘) else: test01(n-1) print("test01***",n) test01(3)
運行結果:
test01: 3
test01: 2
test01: 1
test01: 0
over
test01*** 0
test01*** 1
test01*** 2
test01*** 3
【操作】 使用遞歸函數計算階乘(factorial)
#使用遞歸函數計算階乘 def factorial(n): if n == 1:return 1 return n*factorial(n-1)print(factorial(5)) for i in range(1,6): print(i,"!=",factorial(i))
運行結果:
120
1 != 1
2 != 2
3 != 6
4 != 24
5 != 120
(一)Python入門-5函數:08遞歸函數