Python:函數遞迴

來源:互聯網
上載者:User

標籤:lse   最佳化   lex   年齡   pre   IV   流程分析   調用   返回   

Python:函數遞迴

定義:在調用一個函數的過程中直接或間接的調用該函數本身,稱之為遞迴調用。遞迴調用最多能調用999層。

基本模型:  

def func():    print(‘from func‘)    func()    #直接調用自身    func():

 

def func():    print(‘from func‘)    bar()    #間接調用自身def bar():    print("from bar")    func()func()

雖然以上兩中方式為函數遞迴的基本模型,但往往不能直接這樣使用。因為沒有一個函數的結束條件,僅僅相當於一個死迴圈。

 

遞迴分為兩個重要的階段: 遞推+回溯

  遞推:函數不斷減少問題規模直至最終的終止條件。

  回溯:拿到最終明確的值後,返回給上次調用進行處理,直至初始層。

 

 練習題:解決年齡問題,求出alex的年齡

"""alex 他比佩奇 大兩歲。  4   age(3) + 2佩奇 他比日天 大兩歲。  3   age(2) + 2日天 他比太白 大兩歲。  2   age(1)  + 2太白:我今年23.         1   23"""def age(n):    if n == 1:        return 23    else:        return age(n-1) + 2print(age(4))      #這裡的4表示解決問題的規模

29

 

流程分析:

"""def age(4):    if n == 1:        return 23    else:        return age(3) + 2   23 + 2 + 2 + 2def age(3):    if n == 1:        return 23    else:        return age(2) + 2   23 + 2 + 2         def age(2):    if n == 1:        return 23    else:        return age(1) + 2    23 + 2        def age(1):    if n == 1:        return 23    else:        return age(0) + 2"""

 

  注意在Python:
    1、遞迴調用必須有一個明確的結束條件
    2、在python中沒有尾遞迴最佳化,遞迴調用的效率不高
    3、進入下一次遞迴時,問題的規模必須降低

 

 簡單應用情境:

取出列表  l=[1,2,[3,[4,[5,[6,[7,[8,9,[10]]]]]]]] 中的所有元素

def get(l):    for item in l:        if isinstance(item, list):            get(item)     #如果元素為一個列表,那麼遞迴調用自己把該列表傳給get()函數,進行遞迴調用        else:            print(item)
get(l)

 

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.