Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to Check Whether a String is a Palindrome or not Using Recursion
A palindrome is a string that reads the same forwards and backwards, such as "racecar" or "madam". We can check if a string is a palindrome using recursion by comparing characters from both ends and recursively checking the substring in between.
Recursion works by breaking down the problem into smaller subproblems. For palindrome checking, we compare the first and last characters, then recursively check the remaining substring until we reach the base case.
Syntax
The recursive approach follows this logic ?
def check_palindrome(string):
if len(string) <= 1:
return True
if string[0] == string[-1]:
return check_palindrome(string[1:-1])
else:
return False
Example
Here's a complete program to check if a string is a palindrome using recursion ?
def check_palindrome(my_str):
if len(my_str) <= 1:
return True
else:
if my_str[0] == my_str[-1]:
return check_palindrome(my_str[1:-1])
else:
return False
# Test with different strings
test_strings = ["racecar", "hello", "madam", "python"]
for string in test_strings:
if check_palindrome(string):
print(f"'{string}' is a palindrome")
else:
print(f"'{string}' is not a palindrome")
'racecar' is a palindrome 'hello' is not a palindrome 'madam' is a palindrome 'python' is not a palindrome
How It Works
The recursive function works as follows ?
- Base case: If the string length is 0 or 1, it's automatically a palindrome
-
Comparison: Compare the first character
my_str[0]with the last charactermy_str[-1] -
Recursive call: If they match, recursively check the substring
my_str[1:-1](excluding first and last characters) - Return False: If characters don't match, the string is not a palindrome
Case-Insensitive Palindrome Check
To handle cases like "Racecar", we can make the check case-insensitive ?
def check_palindrome_ignore_case(my_str):
my_str = my_str.lower() # Convert to lowercase
if len(my_str) <= 1:
return True
else:
if my_str[0] == my_str[-1]:
return check_palindrome_ignore_case(my_str[1:-1])
else:
return False
# Test with mixed case strings
test_strings = ["Racecar", "Level", "Hello", "Madam"]
for string in test_strings:
if check_palindrome_ignore_case(string):
print(f"'{string}' is a palindrome (ignoring case)")
else:
print(f"'{string}' is not a palindrome")
'Racecar' is a palindrome (ignoring case) 'Level' is a palindrome (ignoring case) 'Hello' is not a palindrome 'Madam' is a palindrome (ignoring case)
Conclusion
Recursive palindrome checking compares characters from both ends and processes the middle substring recursively. This approach elegantly handles the problem by reducing it to smaller subproblems until reaching the base case.
