Solution Review: Check Palindrome
This review provides a detailed analysis of the solution to check whether a string is a palindrome or not.
We'll cover the following
Solution: Using Recursion
def isPalindrome(testVariable) :# Base Caseif len(testVariable) <= 1 : # Strings that have length 1 or 0 are palindromereturn True# Recursive Caselength = len(testVariable)if testVariable[0] == testVariable[length - 1] : # compare the first and last elementsreturn isPalindrome(testVariable[1: length - 1])return False# Driver Codeprint(isPalindrome("madam"))
Explanation
Our base case will be the condition when we have a string of size or less. In such a case, we can return True
directly.
For the recursive case, we will compare the first and last elements. If they are same, we will call the function isPalindrome()
for the string again, but with the first and last elements removed.
The illustration below shows how we reached our algorithm:
Finally, let’s have a look at the sequence of function calls:
In the next lesson, we have a short quiz on recursion with strings to test your concepts.