English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
En este artículo, aprenderás cómo crear funciones recursivas (funciones que se llaman a sí mismas).
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.
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。
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
Recursive functions make the code look clean and tidy.
Using recursion can decompose complex tasks into simpler subproblems.
Compared to using nested nesting, recursion is easier to generate sequences.
Sometimes, the logic behind recursion is difficult to follow.
Recursive calls are expensive (inefficient) because they consume a large amount of memory and time.
Recursive functions are difficult to debug.