Question

I wrote the following code in python for this problem from Project Euler: Largest palindrome product

y = 1000
x = 1000
while y >= 100:
    y-=1
    while x >= 100:
            x-=1
            product = y*x
            string = str(product)
            if str(product) == string[::-1]:
                    print(product)

But this doesn't output anything in the idle... what is the problem?

Was it helpful?

Solution

You need to re-initialize x inside the outer loop:

while y >= 100:
    x = 1000
    ...

OTHER TIPS

You need to initialise x in the loop. But it's much easier to use for loops, and avoid the issue of initialisation entirely.

for y in range(100, 1000):
    for x in range(100, 1000):
        prod = x * y
        if str(prod) == str(prod)[::-1]:
            print(prod)

## For the beginners... This might help youu!! ##

pro=[]
fin=[]
my_num=[]
x=[]
rev_num=[]

for a in range (100,1000):
    for b in range (100,1000):
        my_num.append(str(a*b))

l1= len(my_num)

for i in range(0,l1):
    rev_num.append(my_num[i][::-1])


for j in range(0,l1):
    if(my_num[j]==rev_num[j]):
        pro.append(int(my_num[j]))


pro.sort()
print(f'Largest palindrome product in the range is {pro[-1]}')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top