Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python- Nested for loops not working as expected

Tags:

python

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:

  1. Am I using/nesting for loops improperly in some way?
  2. Is there a way to search for palindromes without using the two loops?
like image 828
Luke Avatar asked May 30 '26 12:05

Luke


2 Answers

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
like image 164
Yevhen Kuzmovych Avatar answered Jun 02 '26 02:06

Yevhen Kuzmovych


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
like image 45
Will Avatar answered Jun 02 '26 02:06

Will