Finding The Palindrome Using Python

Learn python programming in 12 lessons


A palindrome is defined as a phrase, number or string that reads the same way backwards. A number like 11, 1221, 2002 are all palindromes because they read the same when reversed. There are also strings that can read the same way in reverse such as lol, eye, madam, etc. Words, phrases or numbers that read the same when reversed are called palindromic.

In Python, the easiest way to find the palindrome of a string is to simply reverse the string and use logical operators to check if the two words are the same. For phrases, you might want to reverse the phrase and compare the phrases by ignoring the spaces and punctuation. For numbers, it is easier to convert it to a string and test it using the logical operator. Sometimes it helps to compare the word by ignoring the case and test either as all caps or small caps because "Eye" != "eye" in computing.

Another way of finding the palindrome of a number is to construct the number starting with the digits at the far end working all the way to the front. Notice that a number is a base 10 and to strip of the last digit, you continuously divide by 10 and retain the whole number whilst using the reminder to build a new number.

The following for loop is designed to do just that


# num is the parameter passed to the function
number = num
reversed = 0
for i in range(1,len(num)):   
        r = number % 10
        reversed = reversed * 10 + r * 10
        number = number // 10 #integer division

A simple function to test if a number or letter is a palindrome is as seen below


# This function checks if the word or number is a palindrome

def palindrome(word):
   
    # make sure the parameter is a string
    word = str(word)
   
    # reverse the word
    reversed = word[::-1]
   
    # compare the two words ignoring the case
    if word.lower() == reversed.lower():
        return True # or print ("Palindrome")
    else:
        return False # print("Not a palindrome")

The above code can also be written using a recursive algorithm that slices the character at index 0 and concatenating it with the rest of the string by placing it at the end when reversing the string. The part that reverses the code in the function above can be replaced with the line reversed = reverse(word) where reverse the recursive Python function for reversing a string.


# Recursive function for reversing a string
def reverse(string):
   
    if string == "":
        return string # Base case: empty string
    else: # Recursively reverse the string
        return reverse(string[1:]) + string[0]

Share your thoughts