Search code examples
pythonrecursionpalindrome

Python - palindrome numbers


I am trying to write a program that finds the smallest pallindrome cube. My code:

def cubepal():
    i=3
    if str(i**3)==str(i**3)[::-1]:
        return i**3
    else:
        i=i+1
        cubepal()

I am pretty sure that the first part is correct, but the last three lines make the program run in an endless loop. In the end it only says the problem is on line

if str(i**3)==str(i**3)[::-1]:

I don't see why there is a problem. Could somebody help?


Solution

  • The reason is that you don't scope your variables correctly.

    You call cubepal and cubepal initializes i=3 now when you perform the recursive call, i is a local variable equal to 3.

    def cubepal(i):
        if str(i**3)==str(i**3)[::-1]:
            return i**3
        else:
            return cubepal(i+1)
    

    and call it with cubepal(3).

    Although for such cases, one better not uses recursion: if it is expected that i will be very large (this is not the case here), but it could be, for a memory-inefficient Python interpeter, result in a call-stack that scales with the value of the result.

    A better way to handle this is I guess a while loop.

    def cubepal():
        i = 3
        while str(i**3) != str(i**3)[::-1]:
            i = i+1
        return i**3
    

    This will in general be more efficient as well, because calling a function leads to some overhead regarding bookkeeping and the call-stack.