• Some users have recently had their accounts hijacked. It seems that the now defunct EVGA forums might have compromised your password there and seems many are using the same PW here. We would suggest you UPDATE YOUR PASSWORD and TURN ON 2FA for your account here to further secure it. None of the compromised accounts had 2FA turned on.
    Once you have enabled 2FA, your account will be updated soon to show a badge, letting other members know that you use 2FA to protect your account. This should be beneficial for everyone that uses FSFT.

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