python:遞迴函式

來源:互聯網
上載者:User

標籤:階乘計算   int   分享圖片   lan   沒有   技術   --   程式   ...   

在函數內部我們可以調用其它函數如:

def say(great):    return greatdef person(name):    print(say("Hello"), name)person("珊迪 奇克斯")

列印如下:

 >>> Hello 珊迪 奇克斯

 

但如果我們調用自身,這個函數就是遞迴函式

舉個例子,我們來計算階乘 n! = 1 x 2 x 3 x ... x n(比如5的階乘:5*4*3*2*1)用函數fact(n)表示可以看出:

fact(n) = n! = 1x  2 x  3 x .....x (n - 1) x n = (n - 1) ! x n = fact(n - 1) * n

所以,fact(n)可以表示n * fact(n - 1),只有n = 1時需要特殊處理。(否則1*fact(1 - 1) =0沒有意義)

於是,fact(n) 用遞迴的方式寫出來就是:

def fact(n):    if n == 1:        return 1    return n * fact(n - 1)

上面就是一個遞迴函式,我們把它寫成一個功能方便我們示範結果

detail = input("階乘計算機: 九九參考計算機 按任意鍵繼續\n\n")def face(n):    if n == 1:        return 1    return n * face(n - 1)while True:    num = int(input("輸入數值你想找到的階乘:"))    print("階乘結果是:",face(num))    print("---------------------")

這樣我們就可以示範我們寫的階乘計算機程式了!

如果我們計算fact(5)可以根據函數定義看到計算過程如下:

 

===> fact(5)===> 5 * fact(4)===> 5 * (4 * fact(3))===> 5 * (4 * (3 * fact(2)))===> 5 * (4 * (3 * (2 * fact(1))))===> 5 * (4 * (3 * (2 * 1)))===> 5 * (4 * (3 * 2))===> 5 * (4 * 6)===> 5 * 24===> 120


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

python:遞迴函式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.