Exercise
Recursive Function To Invert A Sequence
Objective
Develop a Python program that utilizes recursion to reverse a sequence of characters. For instance, given the input 'Hello', the program should return 'olleH' by processing the string from the end to the beginning.
Example Python Exercise
Show Python Code
# Function to recursively reverse a string
def reverse_string(s):
# Base case: if the string is empty or only one character, return it
if len(s) == 0:
return s # Return the empty string when no characters are left
else:
# Recursive case: reverse the substring (excluding the first character) and append the first character at the end
return reverse_string(s[1:]) + s[0] # Reverse the substring and add the first character to the result
# Example string
input_string = "Hello"
# Call the function to reverse the string
reversed_string = reverse_string(input_string)
# Print the reversed string
print(f"The reversed string is: {reversed_string}")
Output
python reverse_string.py
The reversed string is: olleH
Share this Python Exercise