I\'m using the Python Tutorial visualize webpage to try and understand the flow of this function that reverses a string:
text = \"hello\"
def reverse(text):
Here's the sequence of recursive calls, and what they return. You'll see that reverse("hello")
returns the result of reverse("ello")
plus "h"
.
reverse("hello")
--> return reverse("ello") + "h"
So then the question is what does reverse("ello")
return?
reverse("ello")
--> return reverse("llo") + "e"
Continuing on...
reverse("llo")
--> return reverse("lo") + "l"
reverse("lo")
--> return reverse("o") + "l"
Finally, it bottoms out when reverse("o")
is called. Here len(text) <= 1
, and so it returns simply "o"
.
reverse("o")
--> return "o"
You can then work your way back up from bottom to top to calculate the return value from the original reverse("hello")
call.
reverse("hello")
-> reverse("ello") + "h"
-> reverse("llo") + "e" + "h"
-> reverse("lo") + "l" + "e" + "h"
-> reverse("o") + "l" + "l" + "e" + "h"
-> "o" + "l" + "l" + "e" + "h"
-> "olleh"
This is to show the purpose of the return reverse(text[1:]) + text[0]
line and its behaviour in action.