SICP-1.7-遞歸函數
阿新 • • 發佈:2017-06-24
斐波那契數 bsp 相互 個人 icp logs ive ast ret
遞歸函數
- 函數內部直接或間接的調用函數自身
- 將復雜問題簡單化
例子程序
-
def sum_digits(n): """Return the sum of the digits of positive integer n.""" if n < 10: return n else: all_but_last, last = n // 10, n % 10 return sum_digits(all_but_last) + last
- 各位數字之和問題分解為兩個步驟
- 除了最後一個數字以外所有數字相加
- 然後加上最後一個數字
相互遞歸
-
def is_even(n): if n == 0: reutrn True else: return is_odd(n-1) def is_odd(n): if n == 0: return False else: return is_even(n-1) result = is_even(4)
- game
- 一個雙人遊戲,桌上有n個鵝卵石,每次一個人能從桌子上拿走一個或兩個鵝卵石,拿走最後一個鵝卵石的人勝利
- Alice每次只拿走一個鵝卵石
- Tom在鵝卵石是偶數的時候拿走兩個鵝卵石,反之拿走一個鵝卵石
- 最終誰會獲勝
-
def play_Alice(n): if n == 0: print("Tom wins!") else: play_Tom(n-1) def play_Tom(n): if n == 0: print("Alice wins!") elif(n%2 == 0): play_Alice(n-2) else: play_Alice(n-1)
樹遞歸
- 一個函數調用自己大於一次
- 例子(斐波那契數列):
-
def Fibo(n): if n == 1:
def count_partitions(n, m): """Count the ways to partition n using parts up to m.""" if n == 0: return 1 elif n < 0: return 0 elif m == 0: return 0 else: return count_partitions(n-m, m) + count_partitions(n, m-1)
- 不斷將函數以m為界分段,直到全部分為1
-
SICP-1.7-遞歸函數