廖雪峰網站:學習python函數—遞迴函式(四)

來源:互聯網
上載者:User

標籤:python函數   bsp   導致   階乘   其他   遞迴函式   棧溢出   學習python   邏輯   

 

 

# 在函數內部,可以調用其他函數。如果一個函數在內部調用自身本身,這個函數就是遞迴函式# 計算階乘n! = 1 x 2 x 3 x ... x n,用函數fact(n)表示,可以看出:# fact(n) = n! = 1 x 2 x 3 x ... x (n-1) x n = (n-1)! x n = fact(n-1) x n# 使用遞迴函式的優點是邏輯簡單清晰,缺點是過深的調用會導致棧溢出。def fact(n):    if n==1:        return 1    return n * fact(n-1)print(‘fact(1) =‘, fact(1))print(‘fact(5) =‘, fact(5))print(‘fact(10) =‘, fact(10))# 利用遞迴函式移動漢漢諾塔:def move (n, a, b, c):    if n == 1:        print(‘move‘, a, ‘-->‘, c)    else:        move(n-1, a, c, b)        move(1, a, b, c)        move(n-1, b, a, c)move(4, ‘A‘, ‘B‘, ‘C‘)

 

廖雪峰網站:學習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.