Don't let the Lockdown slow you Down - Enroll Now and Get 3 Course at 24,999/- Only. Explore Now!

General

Palindrome in Python

Palindrome in Python

A string or a number is a palindrome if the reverse of the said number or string is the same as the string. For example, 101 and madams are number and string palindrome respectively. We will go through some methods to check if a string or a number is a palindrome or not

Method 1

  • Create the reverse of the string or the number
  • Now check if the reverse of the string is the same as the original string.
def palindrome_checker(string):
#Storing the reverse of the string in rev 
rev_string = string[::-1]
#Check if both strings are equal or not 
if (string == rev_string):
return True
return False
s = "madam"
ans = palindrome_checker(s)
print(ans)

Method 2

In this implementation of palindrome_checker, if there are n characters in a word, we will compare the 1st character to the last one, 2nd character to the second last character and so on. If any character mismatches then it cannot be considered as a palindrome.

Below is the implementation of the above approach that has been explained:

import numpy as npdef palindrome_checker(string): 
for index in range(0, int(np.ceil(len(string)/2))): 
if string[index] != string[len(string)-index-1]: 
return False
return True
s = "madam"
ans = palindrome_checker (s) 
print(ans)

Method 3
Using join and reversed functions which

def palindrome_checker(string):
rev_string = ''.join(reversed(string))
if (string == rev_string):
return True
return False
s = "madam"
ans = palindrome_checker(s)
print(ans)

Related Blogs:

  1. Brief Overview of Python Language
  2. Python Career opportunities
  3. Python Break Continue
  4. Python Control Flow
  5. Python Data Types
  6. Python Dictionary
  7. Python Exception Handling
  8.  Python File
  9. Python Functions
  10. Python Substring
Scroll Up
Besant Technologies WhatsApp