I'm fairly new to Python and trying out the Project Euler challenges. I'm currently having trouble getting a nested for loop to work properly. My code looks like this:
def palindrome():
for i in range(999,317,-1):
for a in range(999,317,-1):
s = str(i*a)
if s[0] == s[5] and s[1] == s[4] and s[2] == s[3]:
return(s)
print(palindrome())
The point of the program is to find the largest possible palindrome that is the product of two three digit numbers. When I run this program, I consistently get the answer 580085. It is a palindrome, but I know it's the wrong answer.
Concrete Questions:
Try this:
def palindrome():
return max( i * j for i in range(999, 317, -1)
for j in range(i, 317, -1)
if str(i*j) == str(i*j)[::-1]
)
or more readable way:
def palindrome():
largest = 0
for i in range(999, 317, -1):
for j in range(i, 317, -1):
if str(i*j) == str(i*j)[::-1] and i*j > largest:
largest = i*j
return largest
You're pretty close. Your code is returning the first palindrome it finds, you want to find all palindromes, and only return the largest one. Try something like:
def palindrome():
largest = 0
for i in range(999,317,-1):
for a in range(999,317,-1):
s = str(i*a)
if s[0] == s[5] and s[1] == s[4] and s[2] == s[3]:
if int(s) > largest:
largest = int(s) # <-- don't return, just set s aside and keep checking
return largest
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With