Search code examples
pythonpython-3.xfor-looppalindrome

Palindrome checker not giving all correct values when looped


I'm trying to check if the product of a series of numbers (from 100 to 999) are palindromes. I have my palindrome checker working, but when I try to incorporate it into my loop I don't get all the possible answers.

def pali_check(n):
  n = str(n)
  pali = n[::-1]
  if pali == n:
   print(pali)

for x in range(999,99,-1):
  product = x*(x+1)
  pali_check(product)

I should be getting all palindromes in this range (ex. one is 906609)

However, the only value I get is 289982. How can I fix my code so that it gives me all possible results?


Solution

  • 906609 = 913 * 993
    

    Since you are only checking n*(n+1), you wont find that one

    On the other hand,

    289982 = 538 * 539
    

    so that is why you are finding it

    You should try using a nested loop and multiply the two loop variables together

    for x in range(999, 99, -1):
        for y in range(999, 99, -1):
            product = x * y
            pali_check(product)
    

    You can easily optimise the above to prevent duplicates