Reputation: 11
I have this function here that will print a string until it gets to the last character. The thing is I need it to do the opposite of that.
Instead of 'abc' printing 'abc, ab, c' I need it to print 'c, bc, abc'.
Thank you!
def reverse(string):
if len(string) == 0:
return string
else:
print(string)
return reverse(string[1:])
Upvotes: 1
Views: 572
Reputation: 95908
The base case here is easy: the length of the string is 0, simply return without printing. If it isn't the base case, you have two things to do, keep breaking the string down (recursively), or printing the string. Depending on the order, you can get the results printed in a different order:
>>> def rev(string):
... if string:
... rev(string[1:]) # keep breaking down the string
... print(string) # print the string
... return
... else:
... return
...
>>> rev('abc')
c
bc
abc
Now look if we switch:
>>> def rev(string):
... if string:
... print(string) # print the string
... rev(string[1:]) # keep breaking down the string
... return
... else:
... return
...
>>> rev('abc')
abc
bc
c
Note, you don't really need the else: return
, or the return
after at the end of the if
block, but I kept it in just to be explicit and make you think about what is happening in your function.
Think of yourself as the first, intended version of the function. I receive a string as an argument, and it isn't empty. I then create a duplicate of myself (since we are imagining things) then break down my string and hand it off to him, giving him "control". And he does the same thing: checks if the string is not empty, breaks it down if that is the case, and creates a clone and gives him the new string and control, all the way down until we reach a clone who receives an empty string. This clone simply checks and sees that the string is empty, and returns control to the clone that called him. This clone now does the next step: he prints, and this clone is the clone that got a string with length one... after he is done printing, he returns control to the clone that called him...
Upvotes: 1
Reputation: 13533
Just switch the 2 lines in the else. This will cause all of the recursive calls to happen before any of the print
statements. Once the end of the string is reached, the recursion will unwind and all the print
s will happen:
def reverse(string):
if not string:
return
else:
reverse(string[1:])
print(string)
reverse("abc")
Output:
c bc abc
Upvotes: 2