English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriales Básicos de Python

Control de Flujo de Python

Funciones en Python

Tipos de datos en Python

Operaciones de Archivo de Python

Objetos y Clases de Python

Fecha y Hora de Python

Conocimientos Avanzados de Python

Manual de Referencia de Python

Recursión en Python (Recursión)

En este artículo, aprenderás cómo crear funciones recursivas (funciones que se llaman a sí mismas).

¿Qué es la recursión en Python?

La recursión es el proceso de definir algo en términos de sí mismo.

Un ejemplo físico del mundo real es colocar dos espejos paralelos enfrentados. Cualquier objeto entre ellos se reflejará recursivamente.

función recursiva de Python

En Python, sabemos que unfunciónPueden llamar a otras funciones. Las funciones pueden incluso llamarse a sí mismas. Este tipo de estructuras se denominan funciones recursivas.

A continuación, se muestra un ejemplo de función recursiva para encontrar el factorial de un entero.

el factorial de un número es el producto de1el producto de todos los enteros hasta ese número. Por ejemplo, el factorial6(representado como6!es1 * 2 * 3 * 4 * 5 * 6 = 720

ejemplo de función recursiva

def calc_factorial(x):
    """Esto es un
    """函数用于计算整数阶乘"""
    if x == 1:
        return 1
    else:
        return (x * calc_factorial(x-1))
num = 4
print("El factorial de", num, "es", calc_factorial(num))

In the above example, it calc_factorial() is a recursive function that calls itself.

When we call this function with a positive integer, it will recursively call itself by reducing the quantity.

Each function multiplies the number by the factorial of the number below it until it equals1. This recursive call can be explained in the following steps.

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

when the number is reduced to1when, recursion ends. This is called the basic condition.

Each recursive function must have a basic condition to stop recursion, otherwise the function will call itself infinitely.

The Python interpreter limits the depth of recursion to help avoid infinite recursion, which can lead to stack overflow.

By default, the maximum recursion depth is 1000. If the limit is exceeded, the result will be RecursionError. Let's look at such a condition.

def recursor():
    recursor()
recursor()

Output result

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

The advantages of recursion

  1. Recursive functions make the code look clean and tidy.

  2. Using recursion can decompose complex tasks into simpler subproblems.

  3. Compared to using nested nesting, recursion is easier to generate sequences.

The disadvantages of recursion

  1. Sometimes, the logic behind recursion is difficult to follow.

  2. Recursive calls are expensive (inefficient) because they consume a large amount of memory and time.

  3. Recursive functions are difficult to debug.