Search code examples
pythonmathpalindrome

How to find the largest palindrome made of two three digit numbers in python?


I was trying Problem 4 on Project Euler when I ran into a problem. Here is my code.

def Problem4():
    x = 100
    y = 909
    a = []
    b = []
    x1 = []
    y1 = []
    while y < 1000:
        while x < 1000:
            z = x*y
            if str(z) == str(z)[::-1]:
                a.append(z)
                x1.append(x)
                y1.append(y)
            else:
                b.append(z)
            x = x + 1
        y = y + 1       
    print(a)
    print(x1)
    print(y1)
Problem4()

This code runs okay, but the value of y remains constant, even after the y = y + 1. Why is it doing that? Is there a better way of doing this.


Solution

  • move the x = 100 line to the position between first while loop and the second while loop would solve your problem.

    def Problem4():
        y = 909
        a = []
        b = []
        x1 = []
        y1 = []
        while y < 1000:
            x = 100
            while x < 1000:
                z = x*y
                if str(z) == str(z)[::-1]:
                    a.append(z)
                    x1.append(x)
                    y1.append(y)
                else:
                    b.append(z)
                x = x + 1
            y = y + 1       
        print(a)
        print(x1)
        print(y1)
    Problem4()