一文讲明白 Python 递归

一文讲明白 Python 的递归

一、📌 什么是递归?

递归(Recursion)是指在函数内部调用自己本身的编程技巧。它通常用于解决可以分解为子问题的问题,比如树结构、图遍历等。

简单理解:一个问题的解依赖于它更小规模的子问题的解。


二、🧠 递归的基本结构

1
2
3
4
5
def recursive_function(parameters):
if termination_condition:
return result # 终止条件,防止无限调用
else:
return recursive_function(smaller_parameters)

✅ 必须包含:

  1. 终止条件(Base Case)
  2. 递归调用(Recursive Case)

三、🌱 新手入门:经典案例示例

1. 阶乘计算

1
2
3
4
def factorial(n):
if n == 1:
return 1 # 基本情况
return n * factorial(n - 1) # 递归调用
1
print(factorial(5))  # 输出 120

2. 斐波那契数列(演示递归的效率瓶颈)

1
2
3
4
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)

❗ 该方法效率低,适合用来演示“重叠子问题”的场景。


四、🔍 递归的应用场景(企业级实战)

示例1:📂 遍历嵌套文件夹结构

1
2
3
4
5
6
7
8
9
10
import os

def traverse_directory(path):
for entry in os.listdir(path):
full_path = os.path.join(path, entry)
if os.path.isdir(full_path):
print("📁 目录:", full_path)
traverse_directory(full_path) # 递归进入子目录
else:
print("📄 文件:", full_path)

📌 实用场景:企业系统自动部署、日志批处理、全盘搜索等。


示例2:🌳 树形组织架构数据解析(JSON格式)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
org_chart = {
"name": "CEO",
"children": [
{"name": "CTO", "children": [
{"name": "Dev Manager", "children": []}
]},
{"name": "CFO", "children": []}
]
}

def print_org_chart(node, level=0):
print(" " * level + f"👤 {node['name']}")
for child in node.get("children", []):
print_org_chart(child, level + 1)

print_org_chart(org_chart)

📌 实用场景:企业HR系统组织管理、后台权限树、菜单树等。


示例3:🧾 递归计算订单明细的总价(嵌套结构)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
order = {
"name": "套餐A",
"price": 0,
"items": [
{"name": "汉堡", "price": 20},
{"name": "配菜", "price": 0, "items": [
{"name": "薯条", "price": 10},
{"name": "鸡翅", "price": 12}
]}
]
}

def calc_price(item):
total = item.get("price", 0)
for sub in item.get("items", []):
total += calc_price(sub)
return total

print("总价:¥", calc_price(order)) # 输出:¥42

📌 实用场景:ERP系统、商品打包套餐系统等。


五、⛏️ 常见问题及优化

❓ 问题1:栈溢出(RecursionError)

  • 默认递归深度:1000(可通过 sys.setrecursionlimit 修改)

❓ 问题2:重复计算(如 Fibonacci)

  • ✅ 可使用 ​缓存优化​(如:functools.lru_cache
1
2
3
4
5
6
7
from functools import lru_cache

@lru_cache()
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)

六、⚙️ 企业实战中使用递归的技巧总结

技巧 说明
✅ 设定终止条件 防止死循环或栈溢出
✅ 添加缓存 提升性能(如动态规划+备忘录)
✅ 使用尾递归/转循环 Python不优化尾递归,必要时改用循环
✅ 日志/print辅助调试 观察递归栈的变化

七、📌 小结

阶段 内容
入门 理解递归结构、终止条件
提升 掌握递归在树形/图结构中的应用
实战 构建企业级功能:文件遍历、组织结构、订单价格、权限系统等
优化 使用缓存、转换为循环、控制递归深度

一文讲明白 Python 递归
https://dreamshao.github.io/2025/05/15/python递归/
作者
Yun Shao
发布于
2025年5月15日
许可协议