recursion

J. Clifford Dyer jcd at sdf.lonestar.org
Fri Sep 14 09:43:27 EDT 2007


On Fri, Sep 14, 2007 at 01:40:17PM +0200, Gigs_ wrote regarding Re: recursion:
> 
> what i mean is how python knows to add all thing at the end of recursion
> 
>  >>> def f(l):
>      if l == []:
>          return []
>      else:
>          return f(l[1:]) + l[:1]
> 

The following script does exactly the same thing, except it creates print 
statements to help you figure out what's going on, and it binds f(L[1:]) to 
a variable so you can use it again.

def f(L):  # l capitalized to accentuate difference between l and 1.
    print "L =", L
    print "L[1:] =", L[1:]
    print "L[:1] =", L[:1]
    if L == []:
        print "Return: ", []
        return []
    else:
        next = f(L[1:])
        print "Return: ", next, "+", L[:1], "=", next + L[:1]
        return next + L[:1]

if __name__=='__main__':
    print f(['A', 'B', 'C', 'D'])

Try it out.  See what happens.

Cheers,
Cliff



More information about the Python-list mailing list