Search code examples
pythonlistpalindrome

Why list created by code does not include values greater than 99,999 (Python)


This code is meant to find the largest palindrome created by the product of two 3 digit numbers.

I'm sure that there are more efficient ways to solve this problem, and you're welcome to post them, but at this stage in my learning, I'm most interested in how I could edit the code that I've written to make it work correctly.

When I run this code, it correctly creates a sorted list of palindromes, but the largest number in the list is 99,999. I can't see why the list doesn't extend past this.

def palindromes():
    product_list=[]
    palindrome_list=[]
    for a in range(100,1000):
        for b in range(100,1000):
            product_list.append(a*b)
    for product in product_list:
        product = str(product)
        if len(product) % 2 == 0:
            if product[0]==product[5] and product[1]==product[4] and product[2]==product[3]:
                palindrome_list.append(product)
        if len(product) % 2 != 0:
            if product[0]==product[4] and product[1]==product[3]:
                palindrome_list.append(product)

    palindrome_list = sorted(set(palindrome_list))
    return palindrome_list

print(palindromes()) 

Solution

  • That's because this part is incorrect:

    palindrome_list.append(product)
    

    You were sorting strings, not numbers - even though all the results were appearing in the list, they were being sorted as strings, and appeared in a different order than you expected. Change the above code in the two places where it appears, it should look like this:

    palindrome_list.append(int(product))
    

    Now it's easy to see what's the largest palindrome created by the product of two 3 digit numbers (the last one in the list):

    palindromes()[-1]
    => 906609