📜  Python递归

📅  最后修改于: 2020-09-19 14:57:11             🧑  作者: Mango

### 递归函数示例

``````def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""

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

num = 3
print("The factorial of", num, "is", factorial(num))``````

``The factorial of 3 is 6``

``````factorial(3)          # 1st call with 3
3 * factorial(2)      # 2nd call with 2
3 * 2 * factorial(1)  # 3rd call with 1
3 * 2 * 1             # return from 3rd call as number=1
3 * 2                 # return from 2nd call
6                     # return from 1st call``````

Python解释器限制了递归的深度，以帮助避免无限递归，从而导致堆栈溢出。

``````def recursor():
recursor()
recursor()``````

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

#### 递归的优点

1. 递归函数使代码看起来简洁明了。
2. 可以使用递归将复杂的任务分解为更简单的子问题。
3. 使用递归比使用嵌套嵌套更容易生成序列。

#### 递归的缺点

1. 有时，递归背后的逻辑很难遵循。
2. 递归调用很昂贵(效率低)，因为它们占用大量内存和时间。
3. 递归函数很难调试。