Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23218

If python don't have tail recursion in it, then why my code on leetcode is working differently for different recursions?

$
0
0

As per the link tail recursion is not present in python. I was working on leetcode problem where two inputs are given, number and its power. The power can be negative also. I need to find out exponent using recursion.

This was my code which was not getting accepted:

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

For the above code I received error:

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)....

But for this code, it worked properly:

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)

Viewing all articles
Browse latest Browse all 23218

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>