Python Program to Check Palindrome Using Recursion

1. Introduction

In this tutorial, we will learn how to write a Python program to check if a number is a palindrome or not using the recursion approach.

Recursion is a powerful technique in programming where a function calls itself to solve a problem. In the context of palindromes, recursion can simplify the process of checking if a number is the same forward and backward.

2. Program Steps

1. Define the number to be checked for palindromicity.

2. Create a recursive function to check if the number is a palindrome.

3. Call the recursive function and pass the number to it.

4. Print the result of the recursive check.

3. Code Program

A palindrome is a sequence of characters that reads the same forward and backward. A recursive approach to determine if a number is a palindrome involves comparing the first and last digits and, if they match, recursively checking the remaining middle part.
# Step 1: Define the number
number = 12321

# Recursive function to check for a palindrome
def is_palindrome_recursive(n, original_number=None):
    # Initialize original_number during the first call
    if original_number is None:
        original_number = n

    # Step 2: Base case, if the number has one or no digit, it's a palindrome
    if n < 10:
        return n == (original_number % 10)

    # Remove the last digit and compare it with the first
    if n % 10 != original_number // (10 ** (len(str(n)) - 1)):
        return False

    # Remove the first and last digit and make a recursive call
    n = (n % (10 ** (len(str(n)) - 1))) // 10
    return is_palindrome_recursive(n, original_number // 10)

# Step 3: Call the recursive function
is_palindrome = is_palindrome_recursive(number)

# Step 4: Print the result
print(f"The number {number} is a palindrome: {is_palindrome}")

Output:

The number 12321 is a palindrome: True

Explanation:

1. number is assigned the value 12321.

2. is_palindrome_recursive is defined to check if n is a palindrome. It takes n and an optional original_number parameter, which remains unchanged in recursive calls.

3. If n is less than 10, it means we're down to the last digit, and we compare it with the last digit of original_number.

4. If the current last digit of n doesn't match the current first digit of original_number, it returns False.

5. Otherwise, it strips the first and last digit from n and original_number, respectively, and recurses with the smaller numbers.

6. The final print statement shows the result of the recursive palindrome check.

Comments