Search code examples
list-comprehensionpalindrome

How do you check if a given input is a palindrome?


I need to check if the input is a palindrome.

I converted the input to a string and compared the input with the reverse of the input using list slicing. I want to learn a different way without converting input to a string.

def palindrome(n):
   num = str(n)
   if num == num[::-1]:
      return True

Solution

  • Assuming that n is a number, you can get digits from right to left and build a number with those digits from left to right:

    n = 3102
    m = n
    p = 0
    while m:
         p = p*10 + m%10 # add the rightmost digit of m to the right of p
         m //= 10 # remove the rightmost digit of m
    
    print(p) # 2013
    

    Hence the function:

    def palindrome(n):
        m = n
        p = 0
        while m:
             p = p*10 + m%10
             m //= 10
        return p == n 
    

    Note that:

    if num == num[::-1]:
        return True
    

    will return None if num != num[::-1] (end of the function). You should write:

    if num == num[::-1]:
        return True
    else:
        return False
    

    Or (shorter and cleaner):

    return num == num[::-1]