Trying to find the largest palindrome that's the product of two three-digit numbers. Before I look up the infinitely more efficient and - more importantly - working solution, could you tell me what's wrong with my code? I just keep getting the empty set.
def palindrome():
n = 100
m = 100
palind = []
while n<=999:
while m<=999:
prod = n * m
if str(prod) == str(prod)[::-1] and prod > palind[0]:
palind.pop(0)
palind.append(prod)
return palind
m = m + 1
n = n + 1
return palind
print palindrome()
You have 3 problems.
Problem 1: Returning early.
while n<=999:
while m<=999:
prod = n * m
if str(prod) == str(prod)[::-1] and prod > palind[0]:
palind.pop(0)
palind.append(prod)
# Here
return palind
m = m + 1
n = n + 1
# And here
return palind
A return
statement means the function is over now. It stops where it is, the caller gets the return value, and the caller goes on its way. You don't want to do that until the function is completely done with its work. Let's move the return
to after the loops, when the function is done computing.
Problem 2: palind[0]
is uninitialized.
while n<=999:
while m<=999:
prod = n * m
# Here v
if str(prod) == str(prod)[::-1] and prod > palind[0]:
palind.pop(0)
palind.append(prod)
m = m + 1
n = n + 1
return palind
Suppose your program is going along and it finds its first palindrome. It tries to compare it to palind[0]
, but there is no palind[0]
! You need to take the first palindrome without trying to compare it to one that doesn't exist. Let's fix that.
Problem 3: Not resetting m
.
palind = None
while n<=999:
while m<=999:
prod = n * m
if str(prod) == str(prod)[::-1]:
if palind is None or prod > palind:
palind = prod
m = m + 1
n = n + 1
return palind
After the first iteration of the n
loop, you need to go back through all possible m
values with n=101
. You don't do that; your code keeps m
at 1000
, so it doesn't go through the inner loop again. You could explicitly reset m
, but it's much easier to use for
loops instead of while
s. With all 3 problems fixed, your code looks like
palind = None
for n in xrange(100, 1000):
for m in xrange(100, 1000):
prod = n * m
if str(prod) == str(prod)[::-1]:
if palind is None or prod > palind:
palind = prod
return palind