Python Question

mell0

n00b
Joined
Sep 22, 2005
Messages
28
I'm teaching myself how to program in Python. I've never programmed before, so forgive me for my stupidity. Here's the code that I'm trying to figure out (from a book that I'm using):

Code:
def reverse(s):
    if s == "":
        return s
    else:
        return reverse(s[1:]) + s[0]

I understand that the string's being sliced, but I can't figure out how each element of the string is returned in reverse order. Recursion sucks.
 
Recursion is surprisingly simple once you get used too it.

A simple way to figure it out is to basically "trace" the method step by step.

Take the following method call:

Code:
reverse("blah")

At the point of the return statement, you'll have:

Code:
return reverse("lah") + "b"

If you follow this again, you'll have:

Code:
return (return reverse("ah") + "l") + "b"

Eventually, your call stack will end up like this:

Code:
return (return (return (return (return "") + "h") + "a") + "l") + "b"

Now, you can basically see you have this:

Code:
"" + "h" + "a" + "l" + "b"

which equals "halb".
 
Genius.

Only downside to recursion is the large stack buildup.

But algorithmically, it is beautiful.
 
Back
Top