How to verify a word as a palindrome using recursion
A palindrome is a word that is spelled the same forwards and backwards.
There are multiple ways you can verify if a given word is a palindrome. Some are:
- Using the list
- Using
forloop - Using
reversedfunction
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 "" characterdef 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 stringif word[0] == word[len(word)-1]:return isPalindrome(word[1:len(word)-1])return Falseword = "mom"word = removeNonAlphanumeric(word)print(isPalindrome(word))
We use
regexto convert the word into a non-alphanumeric in theremoveAlphanumeric()function. Comment it if you want to check the word as it is.