Python Program to Reverse a String using Recursion

1. Introduction

Reversing a string is a classic problem that can be solved using various techniques. In the context of programming, a recursive function is one that calls itself in order to divide a problem into smaller, more manageable sub-problems. To reverse a string recursively, we reduce the problem to reversing all but the first character and then appending the first character to the result.

2. Program Steps

1. Define a recursive function that takes a string as input.

2. If the string is empty or has a single character, return the string.

3. Otherwise, call the function recursively with the sub-string excluding the first character, then append the first character.

4. Continue until the base case is reached.

3. Code Program

# Function to reverse a string using recursion
def reverse_recursive(s):
    # Base case: if the string is empty or a single character, return it
    if len(s) <= 1:
        return s
    # Recursive case: reverse the rest of the string and append the first character
    return reverse_recursive(s[1:]) + s[0]

# String to be reversed
input_string = "Recursion"
# Call the recursive function
reversed_string = reverse_recursive(input_string)
# Print the reversed string
print(f"The reversed string is: {reversed_string}")

Output:

The reversed string is: noisruceR

Explanation:

1. reverse_recursive is a recursive function that takes s as its argument.

2. It checks if s is empty or has a single character with len(s) <= 1. If true, it returns s as the base case.

3. If not, the function calls itself with s[1:], which is s without the first character, and then appends the first character s[0] to the result.

4. This process continues, building the reversed string from the end to the beginning, until the base case is met.

5. input_string is set to "Recursion".

6. The function is called with input_string, resulting in the reversed string noisruceR.

7. The result is then printed out, showing the reversal of the input string.

Comments