Jordan E
Jordan E

Reputation: 11

Python loop stops outputting after 99999 even though it should continue

This code is meant to find the largest palindrome from 2 3 digit numbers but stops out puttign well before the final palindrome. Please help.

def palindrome():

    pdrome = -1
    for num in range(100, 1000):
        for num2 in range(100, 1000):
            product = num * num2
            sproduct = str(product)
            length = len(sproduct)
            if length % 2 == 0:
                string1 = sproduct[0:length // 2]
                string2 = sproduct[(length//2) + 1:]
            else:
                string1 = sproduct[0:(length//2)]
                string2 = sproduct[((length//2) + 1):]
            rstring = string2[::-1]
            if string1 == rstring:
                    pdrome = product
    print(pdrome)


palindrome()

Upvotes: 1

Views: 104

Answers (1)

AKX
AKX

Reputation: 168913

If I'm understanding your intent correctly, you could refactor things into a generator that yields all possible palindromes in the given range, then use max() to get the highest one:

def generate_palindromes(a, b):
    for n1 in range(a, b):
        for n2 in range(n1 + 1, b):  # no need to go through all combinations
            number = n1 * n2
            str_number = str(number)
            if str_number == str_number[::-1]:  # It's the same when reversed?
                yield (number, n1, n2)  # Return a 3-tuple, so we can retrieve the factors


highest_palindrome, n1, n2 = max(generate_palindromes(100, 1000))
print(highest_palindrome, n1, n2)

Upvotes: 1

Related Questions