Python學習---遞迴函式的學習

來源:互聯網
上載者:User

標籤:ret   遞迴函式   +=   python   bar   函數   int   false   結構   

定義:在函數內部,可以調用其他函數。如果一個函數在內部調用自身本身,這個函數就是遞迴函式。

遞迴特性:

1. 必須有一個明確的結束條件

2. 每次進入更深一層遞迴時,問題規模相比上次遞迴都應有所減少

3. 遞迴效率不高,遞迴層次過多會導致棧溢出(在電腦中,函數調用是通過棧(stack)這種資料結構實現的,每當進入一個函數調用,棧就會加一層棧幀,每當函數返     回,棧就會減一層棧幀。由於棧的大小不是無限的,所以,遞迴調用的次數過多,會導致棧溢出。)

執行個體1:  (階乘)

# 普通方法def factorial(num):    fac = num    for i in range(1, num):        fac *= i    return facprint(factorial(4))# 遞迴實現def factorial(num):   if num == 1:                     # 結束條件        return 1   return factorial(num - 1) * numprint(factorial(4))# 函數式編程實現:from functools import reduceprint (reduce(lambda x,y: x*y, range(1,5)))  # 24

執行個體2:斐波那契數列

# 普通實現:# 0 1 1 2 3 5 8 13def fibo(n):    before = 0    after = 1    ret = 0    for i in range(n - 1):        ret = before + after        before = after        after = ret    return retprint(fibo(6))                 # 8# 遞迴實現:# 0 1 1 2 3 5 8 13def fibo_new(n):  # n可以為零,數列有[0]    if n <= 1:            # 結束條件   f(0)=0,f(1)=1,f(2)=f(1)+f(0)-->符合return條件,所以<=1        return n    return (fibo_new(n - 1) + fibo_new(n - 2))   # f(8) = f(7) + f(6)print(fibo_new(6))                  #  8# 其他實現def fib(max):    n, b, a = 0, 0, 1    while n < max:        print(b)        b, a = a, b+a  # 賦值是同時執行的        n += 1fib(6)   # 8

 

執行個體3:求number =[2, -5, 9, -7, 2, 5, 4, -1, 0, -3, 8]中的正數的平均值

# 遞迴實現number = [2, -5, 9, -7, 2, 5, 4, -1, 0, -3, 8]count = 0li = []for i in range(len(number)):    if number[i] > 0:        li.append(number[i])        count += 1count = str(count)print("%s個正整數的和為%d" % (count, sum(li)))
# 函數式編程

# 待寫

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.