154k views
2 votes
write a recursive function def reverse(string) that computes the reverse of a string. For example, reverse("flow") should return "wolf" Hint: reverse the substring starting at the second character, then add the first character at the end

1 Answer

2 votes

Answer:

def reverse(s):

if (len(s)>1):

return reverse(s[1:])+s[0]

else:

return s

print reverse("flow")

Step-by-step explanation:

The reverse of a string is the reverse of the substring starting at the 2nd char, followed by the first char. Of course you always need a stop criterium to end the recursion. Only recurse if the string has at least 2 characters.

User Nicolas Dusart
by
5.5k points