什麼是遞迴?

Python 程式面試題實作練習

Kirill Smirnov

Data Science Consultant, Altran

定義

  • 遞迴是一種用自身來定義問題的方式
  • 遞迴是函式把自己當作子程序呼叫的過程
Python 程式面試題實作練習

範例:階乘 $n!$

$n! = n\cdot(n-1)\cdot(n-2)\cdot...\cdot1$

 

$n = 4$:

$4! = 4\cdot3\cdot2\cdot1$

4! = 24

Python 程式面試題實作練習

階乘-迭代法

$n! = n\cdot(n-1)\cdot(n-2)\cdot...\cdot1 = $

$ = 1\cdot2\cdot3\cdot...\cdot n$

迭代解法:

# iterative factorial
def fact_iter(n):
    result = 1
    # looping over numbers from 1 to n
    for num in range(1, n+1)
        result = num * result

    return result

$n = 4$:

result = 1

  1. result = 1 * result(1) = 1
  2. result = 2 * result(1) = 2
  3. result = 3 * result(2) = 6
  4. result = 4 * result(4) = 24

$4! = 1 \cdot 2 \cdot 3 \cdot 4 = 24$

Python 程式面試題實作練習

階乘-遞迴法

$n!$ $=n\cdot(n-1)!$

def fact_rec(n):
    return n * fact_rec(n-1)

那段程式哪裡有問題?

fact_rec(4)
RecursionError

必須定義基底情況!

$n! = n\cdot(n-1)\cdot(n-2)\cdot...\cdot1$

停止條件/基底情況:$1! = 1$

def fact_rec(n):
    if n == 1:
        return 1
    return n * fact_rec(n-1)
fact_rec(4)
24
Python 程式面試題實作練習

重點總結

遞迴函式有兩個重點:

  • 對較小子問題的遞迴呼叫
  • 防止無限呼叫的基底情況
Python 程式面試題實作練習

範例-決策樹

決策樹

用決策樹做分類

Python 程式面試題實作練習

走訪決策樹

走訪決策樹

x-新樣本 $(x_1, x_2)$

# Pseudo algorithm for finding out the category:

category = pred(node, x):
# Check if there is a split if node.hasSplitting:
# Check which child node to take if node.goToLeftChild(x): return pred(node.leftChild, x) if node.goToRightChild(x): return pred(node.rightChild, x)
Python 程式面試題實作練習

走訪決策樹

用決策樹做預測

x-新樣本 $(x_1, x_2)$

# Pseudo algorithm for finding out the category:

category = pred(node, x):
# Check if there is a split if node.hasSplitting:
# Check which child node to take if node.goToLeftChild(x): return pred(node.leftChild, x) if node.goToRightChild(x): return pred(node.rightChild, x)
# Returning the category return node.category
Python 程式面試題實作練習

一起來練習吧!

Python 程式面試題實作練習

Preparing Video For Download...