Python | Check if a string is a palindrome or not using Recursion

Method 1: Using the string slicing method with the recursive approach

def palindrome_or_not(my_str):
   if len(my_str) < 1:
      return True
   else:
      if my_str[0] == my_str[-1]:
         return palindrome_or_not(my_str[1:-1])
      else:
         return False


check_string = str(input("Enter the string for which you want to check whether it is palindrome or not :"))
print("The entered string is ", check_string)

if(palindrome_or_not(check_string)==True):
   print("The entered string is a palindrome")
else:
   print("The entered string isn't a palindrome")

Output:

Enter the string for which you want to check whether it is palindrome or not :repaper
The entered string is  repaper
The entered string is a palindrome

Explanation

Now if the length of the string is less than 1 then we simply return the string that is entered by the user. Now if that is not the case then, we match the first character of the string and the last character of the string. If that matches then we again call the function. The string that we passed on to the function is the sliced string from index 1. In this way, we match the characters of the string from starting and ending characters and finally in the end we decide whether the string is palindrome or not.

Method 2: Using length()

def palindrome_or_not(s, i):
    if(i > len(s)/2):
       return True
    ans = False
    if((s[i] is s[len(s) - i - 1]) and palindrome_or_not(s, i + 1)):
      ans = True
    return ans
 
check_string = str(input("Enter the string for which you want to check whether it is palindrome or not :"))
print("The entered string is ", check_string)

if (palindrome_or_not(check_string, 0)):
   print("The entered string is a palindrome")
else:
   print("The entered string isn't a palindrome")

Explanation:

Here we check for palindromes by traversing through the string. We check to see if the ith and n-i-1th indexes are equivalent. We return false if they are not equal and if they are, then we carry on with the recursive calls. Once the calls are over and all the characters are checked then we set the value of and variable to True and based on that our statement will be printed.

Share:

Author: Ayush Purawr