You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python无尾递归,为何LeetCode递归求幂代码表现不同?

两段递归求幂代码的运行差异原因解析

已知Python不支持尾递归优化,我在LeetCode实现支持负指数的递归求幂功能时,两段代码表现完全不同:第一段触发「RuntimeError: maximum recursion depth exceeded」错误,第二段却能正常运行,请问这是为什么?

未通过的代码

class Solution(object):
    def myPow(self, x, n):
        """
        :type x: float
        :type n: int
        :rtype: float
        """
        def po(x,n):
            if n ==1:
                return x
            if n== 2:
                return x * x

            if n % 2==0:
                return po(x * x, n//2)
            else:
                return x * po(x * x,(n-1)//2)
        
        p = po(x,abs(n))

        if n < 0:
            return float(1)/p
        else:
            return p

报错信息

RuntimeError: maximum recursion depth exceeded
    return po(x * x, n//2)
Line 15 in po (Solution.py)
    return po(x * x, n//2)
Line 15 in po (Solution.py)
.
.
.

正常运行的代码

class Solution(object):
    def myPow(self, x, n):
        """
        :type x: float
        :type n: int
        :rtype: float
        """
        def po(x,n):
            if n ==0:
                return 1
            if n < 0:
                return 1.0/po(x,-1*n)

            if n % 2==0:
                return po(x * x, n//2)
            else:
                return x * po(x * x,(n-1) // 2)
        
        return po(x,n)

核心原因分析

两段代码的差异根源在于递归终止条件的完整性:

  • 未通过代码的致命缺陷:
    内部函数po仅处理了n=1和n=2的终止情况,完全忽略了n=0的场景。当输入n=0时,主函数会调用po(x, abs(0))=po(x,0),进入函数后n既不满足等于1/2的条件,又会触发n%2==0分支,递归调用po(x*x, 0//2=0),形成无限递归,最终触发递归深度超限错误。此外,当n为极大值时(比如n=2^1000),递归深度会接近Python默认的递归深度上限(约1000),也可能触发栈溢出。
  • 正常运行代码的优势:
    首先处理了n=0的终止条件,直接返回1,从根源避免了无限递归。同时内置了负指数处理逻辑,无需在主函数中单独取绝对值,进一步减少了异常场景的出现。

内容的提问来源于stack exchange,提问作者Noobie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 00:11:09