4.5k views
5 votes
Write code to create a recursive function to reverse a string.

Example: reverse(‘spoons’) should return ‘snoops’

1 Answer

4 votes

Final answer:

To reverse a string using recursion in Python, define a function called reverse_string that takes a string as input. The base case is when the length of the string is 0 or 1, in which case the string itself is returned. For longer strings, concatenate the result of the function called recursively on the substring starting from the second character with the first character.

Step-by-step explanation:

To create a recursive function to reverse a string in Python, you can define a function called reverse_string that takes a string as input. The base case for the recursion is when the length of the string is 0 or 1, in which case we can simply return the string itself. For longer strings, we can call the reverse_string function recursively on the substring starting from the second character, and then concatenate the first character at the end. Here's the code:

def reverse_string(s):
if len(s) <= 1:
return s
return reverse_string(s[1:]) + s[0]

# Testing the function
input_string = 'spoons'
reversed_string = reverse_string(input_string)
print(reversed_string) # Output: 'snoops'

User Skrrgwasme
by
8.2k points