Search code examples
pythonpython-3.xpalindrome

Compare two python codes


I've been solving Euler project problems, it's the forth one now (we should find the largest palindrome number made from the product of 3-digit numbers.

Anyone knows why the first code works properly, but the second one doesn't? First:

highest = 0
product = 0
def PalDetect(number):
    return str(number) == str(number)[::-1]

ThreeDigits = [i for i in range(100, 1000)]

for i in ThreeDigits:
    for j in ThreeDigits:
        product = i*j
        if (PalDetect(product)) and (product > highest):
            highest = product 

print(highest)

Second:

product = 0
def PalDetect(number):
    return str(number) == str(number)[::-1]

ThreeDigits = [i for i in range(100, 1000)]
for i in ThreeDigits:
    for j in ThreeDigits:
        if PalDetect(i*j):
            product = i*j

print(product)

I expected the second one works properly, and I still don't know why it doesn't.


Solution

  • Code 1 updates the highest variable only if the product is a palindrome and greater than the current highest. This ensures that it finds the largest palindrome. Code 2 updates product to every palindrome it encounters, regardless of its value compared to previous palindromes. This means it only prints the last palindrome found, which might not be the largest.

    Modify Code 2 to track and update the highest palindrome similar to Code 1:

    highest = 0
    product = 0
    
    def PalDetect(number):
        return str(number) == str(number)[::-1]
    
    ThreeDigits = [i for i in range(100, 1000)]
    
    for i in ThreeDigits:
        for j in ThreeDigits:
            product = i * j
            if PalDetect(product) and product > highest:
                highest = product
    
    print(highest)