如果Python中没有尾递归,那么为什么我在leetcode上的代码对于不同的递归有不同的工作方式?

问题描述 投票:0回答:1

根据link,Python 中不存在尾递归。我正在研究 leetcode 问题,其中给出了两个输入:数字及其幂。功率也可以为负。我需要使用递归找出指数。

这是我的代码,但没有被接受:

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)
python recursion tail-recursion
1个回答
1
投票

尾递归不是问题。

在原代码中,如果

n
0
,就会一直递归下去,直到达到最大递归限制。它通过了
1
2
的检查,然后,由于
0
是偶数,它会检查
return po(x * x, n//2)
。因为
n//2
也是
0
,所以它永远不会结束。您只需添加检查
n
是否等于
0

© www.soinside.com 2019 - 2024. All rights reserved.