Skip to content

RecursionError: 最大值 recursion 深度 exceeded

错误信息

                最大值 recursion 深度 exceeded
              

快速摘要

你的 recursive 函数 exceeded Python's 最大值 call stack 深度 (默认 ~1000), 通常 due 到 missing or 不正确基础情况.

为什么发生

  • Missing 基础情况 — recursion 从不停止

  • 基础情况条件是 从不 reached

  • Recursion 深度是 genuinely 也 deep for problem

  • Accidental 无限 recursion (函数 calls 它自己使用相同 args)

最小示例

✗ 错误代码
def countdown(n):
    print(n)
    countdown(n - 1)  # No base case!

countdown(5)  # RecursionError
✓ 修复代码
def countdown(n):
    if n < 0:  # Base case
        return
    print(n)
    countdown(n - 1)

countdown(5)

原始有 否基础情况, 所以它 recurses forever. 添加 '如果 n < 0: 返回' 停止 recursion.

如何诊断

  • 检查那个基础情况是 正确 and reachable

  • Print 实参 at 每个 call 到 see 如果它们 progress

  • Increase 限制使用 sys.setrecursionlimit() (temporary fix)

如何修复

  • 添加 or fix 基础情况所以 recursion terminates

  • Convert recursive 函数到 iterative one

  • Use sys.setrecursionlimit() 如果深度是 legitimately 高

如何预防

  • 总是定义正确基础情况之前 recursive 情况

  • Prefer iteration for 简单循环 (Python isn't optimized for recursion)

  • 测试使用小 输入首先

相关资源

相关术语

相关课程

← 返回语言