简体   繁体   中英

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?

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.

You probably meant to do this:

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

print(cubepal(3))

which yields "343".

Of course, there is no point to do it this way in Python since Python lacks TCO.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM