Program to Check Whether a String is a Palindrome or not Using Recursion

Python Program to Check Whether a String is a Palindrome or not Using Recursion

Are you new to the java programming language? We recommend you to ace up your practice session with these Basic Java Programs Examples

Recursion in Python:

When a function calls itself and loops until it reaches the intended end state, this is referred to as recursion. It is based on the mathematics idea of recursive definitions, which define elements in a set in terms of other members in the set.

Each recursive implementation contains a base case in which the desired state is reached, and a recursive case in which the desired state is not reached and the function enters another recursive phase.

On each step, the behavior in the recursive situation before the recursive function call, the internal self-call, is repeated. Recursive structures are beneficial when a larger problem (the base case) can be solved by solving repeated subproblems (the recursive case) that incrementally advance the program to the base case.
It behaves similarly to for and while loops, with the exception that recursion moves closer to the desired condition, whereas for loops run a defined number of times and while loops run until the condition is no longer met.

In other words, recursion is declarative because you specify the desired state, whereas for/while loops are iterative because you provide the number of repeats.

Strings in Python:

A string is typically a piece of text (sequence of characters). To represent a string in Python, we use ” (double quotes) or ‘ (single quotes).

Examples:

Example1:

Input:

given string = "btechgeeksskeeghcetb"

Output:

The given string [ btechgeeksskeeghcetb ] is a palindrome

Example2:

Input:

given string = "aplussulpa"

Output:

The given string [ aplussulpa ] is a palindrome

Program to Check Whether a String is a Palindrome or not Using Recursion

Below are the ways to Check Whether a String is a Palindrome or not using the recursive approach in Python:

1)Using Recursion (Static Input)

Approach:

  • Give some string as static input and store it in a variable.
  • Pass the string to a recursive function checkPalindromeRecursion function as an argument.
  • Calculate the length of the string using the len() function.
  • If the length of the string is less than 1, the function returns True.
  • If the end letter is the same as the initial letter, execute the function recursively with the parameter as the sliced list with the first and last characters deleted, otherwise return False.
  • Use an if statement to determine whether the given string is True or False and then print the result.
  • If the function returns true then the given string is a palindrome.
  • Else the given string is not a palindrome.
  • The exit of the program.

Below is the implementation:

# function which checks the given string is palindrome or not using recursion
# if th given string is palindrome then it is true else the string is false.


def checkPalindromeRecursion(givenstr):
  # Calculate the length of the string using the len() function.
    stringLen = len(givenstr)
    # If the length of the string is less than 1, the function returns True.
    if stringLen < 1:
        return True
    else:
      # If the end letter is the same as the initial letter, execute the function
      # recursively with the parameter as the sliced list
      # with the first and last characters deleted, otherwise return False.
      # Use an if statement to determine whether the given string is
      # True or False and then print the result.
        if givenstr[0] == givenstr[-1]:
            return checkPalindromeRecursion(givenstr[1:-1])
        else:
            return False


# Give some string as static input and store it in a variable.
given_str = 'btechgeeksskeeghcetb'
# Pass the string to a recursive function checkPalindromeRecursion function as an argument.
# If the function returns true then the given string is a palindrome.
if(checkPalindromeRecursion(given_str)):
    print("The given string [", given_str, '] is a palindrome')
# Else the given string is not a palindrome.
else:
    print("The given string", given_str, 'is not a palindrome')

Output:

The given string [ btechgeeksskeeghcetb ] is a palindrome

2)Using Recursion (User Input)

Approach:

  • Give some random string as user input using the input() function and store it in a variable.
  • Pass the string to a recursive function checkPalindromeRecursion function as an argument.
  • Calculate the length of the string using the len() function.
  • If the length of the string is less than 1, the function returns True.
  • If the end letter is the same as the initial letter, execute the function recursively with the parameter as the sliced list with the first and last characters deleted, otherwise return False.
  • Use an if statement to determine whether the given string is True or False and then print the result.
  • If the function returns true then the given string is a palindrome.
  • Else the given string is not a palindrome.
  • The exit of the program.

Below is the implementation:

# function which checks the given string is palindrome or not using recursion
# if th given string is palindrome then it is true else the string is false.


def checkPalindromeRecursion(givenstr):
  # Calculate the length of the string using the len() function.
    stringLen = len(givenstr)
    # If the length of the string is less than 1, the function returns True.
    if stringLen < 1:
        return True
    else:
      # If the end letter is the same as the initial letter, execute the function
      # recursively with the parameter as the sliced list
      # with the first and last characters deleted, otherwise return False.
      # Use an if statement to determine whether the given string is
      # True or False and then print the result.
        if givenstr[0] == givenstr[-1]:
            return checkPalindromeRecursion(givenstr[1:-1])
        else:
            return False


# Give some random string as user input using the input()
# function and store it in a variable.
given_str = input('Enter some random string = ')
# Pass the string to a recursive function checkPalindromeRecursion function as an argument.
# If the function returns true then the given string is a palindrome.
if(checkPalindromeRecursion(given_str)):
    print("The given string [", given_str, '] is a palindrome')
# Else the given string is not a palindrome.
else:
    print("The given string", given_str, 'is not a palindrome')

Output:

Enter some random string = aplussulpa
The given string [ aplussulpa ] is a palindrome

Explanation:

  • A string must be entered by the user.
  • A recursive function gets the string as an argument.
  • If the length of the string is less than one, the function returns True.
  • If the end letter is the same as the initial letter, the function is repeated recursively with the argument as the sliced list with the first and last characters removed, otherwise, false is returned.
  • The if statement is used to determine whether the returned value is True or False, and the result is printed.

Related Programs: