Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is n power of three – Python

Leet-Code 326. Power of Three: Question Link: https://leetcode.com/problems/power-of-three/description/

My Code:

 class Solution:
    def isPowerOfThree(self, n: int) -> bool:
        print(n)
        if n % 3 == 0:
            if n == 3:
                return True 
            return self.isPowerOfThree(n/3)
        else: return False

I a getting the following error. Any help!
RecursionError: maximum recursion depth exceeded while getting the str of an object

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your function has no way of handling 0. If you step through the function, you print "0" (which is why it’s the first thing that fails after exceeding the recursion depth), then it evaluates 0 % 3 == 0. That’s True, so it goes further. 0 == 3 is False, so it returns self.isPowerOfThree(0), and you’re back where you started (infinite recursion).

Hope this helped.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading