Python遞迴函式介紹

來源:互聯網
上載者:User

標籤:com   自己   必須   分享圖片   ==   ima   技術分享   過多   color   

                  Python遞迴函式介紹

                                尹正傑

著作權聲明:原創作品,謝絕轉載!否則將追究法律責任。

 

 

 

 

一.遞迴函式的工作原理

1.案例展示

 1 #!/usr/bin/env python 2 #_*_coding:utf-8_*_ 3 #@author :yinzhengjie 4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ 5 #EMAIL:[email protected] 6  7  8 import sys 9 # print(dir(sys))10 # sys.setrecursionlimit(1000000)          #修改預設遞迴調用的次數,不建議修改!11 # print(sys.getrecursionlimit())        #查看遞迴函式的最大可以調用的次數,預設是可以調用1000次;12 13 14 def Age(n):15     if n == 5:      #指定明確的遞迴結束條件;16         return 1817     return Age(n+1)+218 19 20 print(Age(1))21 22 """23 遞迴函式:24         1>.遞迴函式必須要有一個明確的結束條件25             遞迴函式效率低,需要在進入下一次遞迴是保留當前的狀態,解決方案是尾遞迴,即在函數的最後一步26 (而非最後一行)調用自己,但是Python又沒有尾遞迴,且對遞迴層級做了限制。27         2>.每次進入更深一層遞迴時,問題規模相比上次遞迴都應有所減少;28         3>.遞迴效率不高,遞迴層次過多會導致棧溢出;29 30 """31 32 33 34 35 #以上代碼執行結果如下:36 26

2.圖解遞迴函式

二.小試牛刀

 1 #!/usr/bin/env python 2 #_*_coding:utf-8_*_ 3 #@author :yinzhengjie 4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ 5 #EMAIL:[email protected] 6  7  8  9 10 def PiercingEye(List):11     for item in List:12         if isinstance(item, list):13             PiercingEye(item)14         else:15             print(item)16 17 18 ListNum = [1, [2, 3, [4, [5, 6, 7, [8, 9]]]]]19 PiercingEye(ListNum)20 21 22 23 24 #以上代碼執行結果如下:25 126 227 328 429 530 631 732 833 9

 

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.