Reputation: 455
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?
Upvotes: 0
Views: 239
Reputation: 18927
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.
Upvotes: 1
Reputation: 477160
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.
Upvotes: 1