1. 程式人生 > >3、遞歸

3、遞歸

函數 color tin pre agg bsp 操作 所有 代碼

3、遞歸

  3.1 基線條件和遞歸條件

    每個遞歸函數都有兩部分:基線條件(base case)和遞歸條件(recursive case)。

    遞歸條件指的是函數調用自己,而基線條件則指的是函數不再調用自己,從而避免形成無限循環。

    代碼清單3-1 遞歸

# -*- coding:UTF-8 -*-
def countdown(i):
    print i
    # 基線條件
    if i <= 0:
        return
    # 遞歸條件
    else:
        countdown(i-1)


print
countdown(5)

  3.2 棧

    棧是一種簡單的數據結構。

    代碼清單3-2 調用棧

# -*- coding:UTF-8 -*-
def greet(name):
    print "hello, " + name + "!"
    greet2(name)
    print "getting ready to say bye..."
    bye()


def greet2(name):
    print "how are you, " + name + "?"


def bye():
    print
"ok bye!" greet("maggie") # result: # hello, maggie! # how are you, maggie? # getting ready to say bye... # ok bye!

    代碼清單3-3 遞歸調用棧

# -*- coding:UTF-8 -*-
# 計算階乘的遞歸函數


def fact(x):
    if x == 1:
        return 1
    else:
        return x * fact(x-1)


print fact(3)

    遞歸指的是調用自己的函數。

    每個遞歸函數都有兩個條件“基線條件和遞歸條件。

    棧由兩種操作:壓入和彈出。

    所有函數調用都進入調用棧。

    調用棧可能很長,這將占用大量的內存。

3、遞歸