Recursive function

Hello,

I’d like to understand recursive functions. I have this example:

Write a recursive function that computes the reverse of a string. For example, reverse(“flow”) should return “wolf”. Reverse the substring starting at the second character then add the first character at the end. For example, to reverse “flow”, first reverse “low” to “wol”, then add the “f” at the end.

##
#  Display the characters in a string in reverse order.
#

def main() :
   inputStr = input("Enter a string: ")
   print(reverse(inputStr))

## Reverse the characters in a string.
#  @param string the string to reverse
#  @returns a string holding the characters in the reverse order
#
def reverse(string) :
   if string != "":
      return string[len(string) - 1] + reverse(string[0 : len(string) - 1])
   return ""

# Call the main function.
main()

I’d like to understand what happens in that return line with reverse. For example if the word is London, I thought it would return, for:
string[len(string) - 1] + reverse(string[0 : len(string) - 1])
N + LONDO

But if I add a print line after the return, it shows something else:

Enter a string:  London
L
oL
L
noL
L
oL
L
dnoL
L
oL
L
noL
L
oL
L
odnoL
L
oL
L
noL

...

Etc

So not sure what’s going on. How would you do the hand tracing?

Also, why does return " " mean? I couldn’t find that.

Thanks!(edited)

Thanks!

You have the right idea. Follow your line of thinking a bit farther.
In your example the next time the string is evaluated it is “NLONDO”
So, taking the last character and prepending it to the remainder of the string yields NOLOND

To answer your other question, that second “return” is the fall-through when the if condition evaluates to false and it becomes the flag for the iteration to end because the very next time the iterative function is evaluated the if is false.

Thanks!, I got it, I’m so happy. Very concise and clear your explanation. That’s what I wanted. :smile:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.