Search code examples
pythonpalindrome

wrong output while invoking the palindrome function through another program


I am trying to solve this problem

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.

Below is the code I have used to find if a number is Palindrome.

 #largest product of two  digit no.s  which is a palindrome eg 91*99 = 9009
        def check_palindrome(str):
            x = len(str)
            for i in range(x//2):
                if str[i] == str[x-1-i]:
                    flag = 0
                else:
                    flag = 1
            if flag== 0:
                print "palindrome"
            else:
                print " not palindrome"
        check_palindrome('9009')
i= 91
j= 99
product = i* j
print product
check_palindrome('product')

When i invoke the function check_palindrome() after calculating product, the program gives wrong output while it gives the correct output when called individually.


Solution

  • You are passing the literal string "product", which is not a palindrome, to your palindrome function:

    check_palindrome('product')
    

    Remove the single quotations and convert to a string:

    check_palindrome(str(product))
    

    to pass the string representing the integer stored in product.


    As an aside, here is an easy way to test if a string is a palindrome:

    def check_palindrome(s):
        return s == s[::-1]
    

    which compares the reverse of the string s with itself. It's a palindrome if both are equal.