Python 基礎(chǔ)教程

Python 流程控制

Python 函數(shù)

Python 數(shù)據(jù)類型

Python 文件操作

Python 對(duì)象和類

Python 日期和時(shí)間

Python 高級(jí)知識(shí)

Python 參考手冊(cè)

Python 遞歸(Recursion)

在本文中,您將學(xué)習(xí)如何創(chuàng)建遞歸函數(shù)(調(diào)用自身的函數(shù))。

什么是Python中的遞歸?

遞歸是根據(jù)自身定義某些內(nèi)容的過程。

一個(gè)物理世界的示例是放置兩個(gè)彼此面對(duì)的平行反射鏡。它們之間的任何對(duì)象都將遞歸地反映出來。

Python遞歸函數(shù)

在Python中,我們知道一個(gè)函數(shù)可以調(diào)用其他函數(shù)。函數(shù)甚至可能會(huì)調(diào)用自身。這些類型的構(gòu)造稱為遞歸函數(shù)。

以下是查找整數(shù)的階乘的遞歸函數(shù)的示例。

數(shù)字的階乘是從1到該數(shù)字的所有整數(shù)的乘積。例如,階乘6(表示為6?。┦?samp>1 * 2 * 3 * 4 * 5 * 6 = 720。

遞歸函數(shù)示例

def calc_factorial(x):
    """這是一個(gè)
    求整數(shù)階乘的遞歸函數(shù)"""

    if x == 1:
        return 1
    else:
        return (x * calc_factorial(x-1))


num = 4
print("The factorial of", num, "is", calc_factorial(num))

在上面的示例中,它c(diǎn)alc_factorial()是一個(gè)遞歸函數(shù),它調(diào)用了自己。

當(dāng)我們用正整數(shù)調(diào)用此函數(shù)時(shí),它將通過減少數(shù)量來遞歸調(diào)用自身。

每個(gè)函數(shù)將數(shù)字乘以該數(shù)字下面的數(shù)字的階乘,直到它等于1。可以在以下步驟中解釋此遞歸調(diào)用。

calc_factorial(4)              # 1st call with 4
4 * calc_factorial(3)          # 2nd call with 3
4 * 3 * calc_factorial(2)      # 3rd call with 2
4 * 3 * 2 * calc_factorial(1)  # 4th call with 1
4 * 3 * 2 * 1                  # return from 4th call as number=1
4 * 3 * 2                      # return from 3rd call
4 * 6                          # return from 2nd call
24                             # return from 1st call

當(dāng)數(shù)字減少到1時(shí),遞歸結(jié)束。這稱為基本條件。

每個(gè)遞歸函數(shù)必須具有停止遞歸的基本條件,否則該函數(shù)將無限調(diào)用自身。

Python解釋器限制了遞歸的深度,以幫助避免無限遞歸,從而導(dǎo)致堆棧溢出。

默認(rèn)情況下,最大遞歸深度為 1000。如果超出限制,則結(jié)果為RecursionError。讓我們看一個(gè)這樣的條件。

def recursor():
    recursor()
recursor()

輸出結(jié)果

Traceback (most recent call last):
  File "<string>", line 3, in <module>
  File "<string>", line 2, in a
  File "<string>", line 2, in a
  File "<string>", line 2, in a
  [Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded

遞歸的優(yōu)點(diǎn)

  1. 遞歸函數(shù)使代碼看起來干凈整潔。

  2. 使用遞歸可以將復(fù)雜的任務(wù)分解為更簡(jiǎn)單的子問題。

  3. 與使用嵌套嵌套相比,使用遞歸更容易生成序列。

遞歸的缺點(diǎn)

  1. 有時(shí),遞歸背后的邏輯很難遵循。

  2. 遞歸調(diào)用很昂貴(效率低),因?yàn)樗鼈冋加么罅績(jī)?nèi)存和時(shí)間。

  3. 遞歸函數(shù)很難調(diào)試。

丰满人妻一级特黄a大片,午夜无码免费福利一级,欧美亚洲精品在线,国产婷婷成人久久Av免费高清