Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

How to verify a word as a palindrome using recursion

Arslan Bajwa

A palindrome is a word that is spelled the same forwards and backwards.

Example of a palindrome

There are multiple ways you can verify if a given word is a palindrome. Some are:

  1. Using the list
  2. Using for loop
  3. Using reversed function

All of these methods are covered here.

Recursive approach

We will first compare the first and last character of the word. If they match, we will check the entire word recursively, excluding the first and last character until the length of the word becomes less than 2. We then return true in this case.

If any of the recursive calls have a different first or last character that’s different from the other, we return false.

import re as regex  # regex library to remove non-alphanumeric from word

# sub() replaces all non-alphanumeric characters with "" character
def removeNonAlphanumeric(word):
    return regex.sub("[^a-zA-Z0-9]+", "", word)

def isPalindrome(word):
        if len(word) < 2:
                return True
        # comparing the first and the last character 
        # and calling the function with the remaining string
        if word[0] == word[len(word)-1]:
                return isPalindrome(word[1:len(word)-1])
        return False

word = "mom"
word = removeNonAlphanumeric(word)
print(isPalindrome(word))

We use regex to convert the word into a non-alphanumeric in the removeAlphanumeric() function. Comment it if you want to check the word as it is.

RELATED TAGS

python
communitycreator
RELATED COURSES

View all Courses

Keep Exploring