Reverse a string
Do your part after the smaller call returns, and the answer builds on the way back. About 9 minutes.
Calls wait for each other
When a function calls itself, it pauses and waits, like a manager handing a task to an assistant. The smaller call runs, maybe calls again, and so on down to the base case. Then the calls finish one by one in reverse: the deepest returns first, and each waiting call picks up where it paused.
This pile of paused calls is called the call stack.
reverse("cat") can't answer yet. It asks reverse("at") and waits, holding on to its letter c.
Your part can go after the call
To reverse "cat", reverse the rest, "at", which gives "ta". Then put the first letter, c, at the end: "tac". The smaller call does most of the work, and your part is just placing one letter.
Where you put it, before or after the returned answer, decides the order of the result.
def reverse_string(s):
if len(s) <= 1:
return s
return reverse_string(s[1:]) + s[0]reverse("dog") returns reverse("og") + "d". What does reverse("og") return?
- A"go"
- B"og"
- C"g"
Show the answer
"go". reverse("og") is reverse("g") + "o" = "g" + "o". So the full answer is "go" + "d" = "god".
Reverse a string
Return s written backwards. Use recursion: reverse everything after the first letter with a smaller call, then place the first letter where it belongs.
s = "cat" → "tac"
0 ≤ length of s ≤ 500 · letters, digits and spaces · one call per letter, so at most 500 calls deep