Palindrome in Python: How to check a number is palindrome?

PythonServer Side ProgrammingProgramming

What is a palindrome?

A palindrome is a string that is the same when read from left to right or from right to left. In other words, a palindrome string is the one whose reverse is equal to the original string.

For example, civic, madam are palindromes.

Cat is not a palindrome. Since its reverse is tac, which is not equal to the original string (cat).

Write a program to find whether the input string is a palindrome or not.

Method 1 - Find Reverse of the string

  • The main thing required in the program is to find the reverse of the string.

  • The reverse can be found using any of the methods of reversing a string. We will be using the simple slicing method to reverse the string. The inbuilt ‘’.join(reversed()) can also be used. Though there are other ways to reverse a string, we will go with a simple one.

  • Compare the reversed string with the original string.

  • Return true if both the strings are equal, else return false.

Example

def isPalindrome(s):
   rev=s[::-1]
   if(rev==s):
      return True
   return False
print("Enter a string")
st=input()
print(isPalindrome(st))

Output

Enter a string
madam
True

Method 2 - Without finding the reverse of the string

The idea is to continuously compare the characters at first and last index of the string until they are unequal.

We shall see two examples without finding the reverse of a string −

String value "madam":

  • We compare first and last characters which are equal, further we compare second and second last characters which are again equal. Last we are only left with one character. Thus, the string is a palindrome.

String Value "reader":

  • The characters are equal till comparison between second and second last element.

    When third and third last characters are compared, they are not equal, hence it is not a palindrome.

  • We can implement this idea through recursion or using two pointers. We will be implementing using two pointers. We start with start pointer at 0 and end pointer at last index. We start comparing and if characters are equal, we increment start pointer and decrement end pointer (thus bringing them to second and second last character and so on).

  • When do we return false? If we find that characters for any set of pointers are not equal, we need not look for further indexes and we can return False.

  • When do we return True? In the other case, if string is a palindrome, we will return True when both the pointers become equal (only 1 character is left to check) or start pointer exceeds the end pointer (all the characters are checked) and hence return true.

Example

def isPalindrome(s):
   rev=s[::-1]
   if(rev==s):
      return True
   return False
print("Enter a string")
st=input()
print(isPalindrome(st))

Output

Enter a string
reader
False
>>>
Enter a string
madam
True
raja
Published on 10-Mar-2021 14:22:51
Advertisements