Reputation: 21
def reverse(text):
if text == "":
return text
else:
return reverse(text[1:]) + text[0]
print(reverse("Hello World!")[:-1])
I want to remove the first character of the string and then reverse it. I know how to do it without recursion, but I'm really confused on how to do so.
Above is the only way I could think of. I just need hints, full answers will be helpful though I'd prefer just hints.
Requirements
Upvotes: 1
Views: 2224
Reputation: 4137
Just an extra tip when it comes to recursion.
Recursion can be really confusing. If you add some prints it can be easier to grasp.
Altering the code adding ->
for input and <-
for a return we can see the recursion depth and all input and output values.
def reverse(text, depth=0):
print("{} -> {}".format(" " * depth, text))
if len(text) <= 1:
print("{} <- ''".format(" " * depth))
return ""
else:
tmp = text[-1] + reverse(text[:-1], depth=depth + 1)
print("{} <- {}".format(" " * depth, tmp))
return tmp
s = reverse("Hello World!")
print(s)
Would output:
-> Hello World!
-> Hello World
-> Hello Worl
-> Hello Wor
-> Hello Wo
-> Hello W
-> Hello
-> Hello
-> Hell
-> Hel
-> He
-> H
<- ''
<- e
<- le
<- lle
<- olle
<- olle
<- W olle
<- oW olle
<- roW olle
<- lroW olle
<- dlroW olle
<- !dlroW olle
Upvotes: 1
Reputation: 82899
If you really want a recursive solution, just change your termination condition to stop one character "too early". Also, invert the order how the characters are popped from the string, otherwise the last character will be dropped.
def reverse(text):
if len(text) <= 1:
return ""
else:
return text[-1] + reverse(text[:-1])
Example
>>> reverse("Hello World!")
!dlroW olle
Upvotes: 3