Search code examples
pythonmathpalindrome

Project Euler: Largest palindrome (Python). What did I do wrong?


I may have done many things wrong as I am only a beginner. But would someone please help me? The goal is to print the largest palindrome made from the product of two 3-digit numbers. Thanks.

palindromes = []
for i in range(100, 1000):
    for x in range(100, 1000):
        a = x*i
        str(a)
        b = a[::-1]
        if a == b :
            palindromes.append(a)

print (palindromes[len(palindromes) - 1])

Solution

  • Basic points:

    • When you convert the number to a string, you have to store the result.
    • Sort the list when you're done.
    • Use right-end indexing to get the last element
    • When you find a palindrome, keep the integer form, so the sort works properly. Otherwise, you get '99999' as the largest palindrome.

    Code:

    palindromes = []
    for i in range(100, 1000):
        for x in range(100, 1000):
            a = str(x*i)
            b = a[::-1]
            if a == b :
                palindromes.append(int(a))
    
    print (sorted(palindromes)[-1])