recursion

Tom Wright tew24 at spam.ac.uk
Thu Sep 13 10:08:44 EDT 2007


Gigs_ wrote:
> Can someone explain me this
> def f(l):
>   if l == []:
>     return []
>   else:
>     return f(l[1:]) + l[:1]  # <= cant figure this, how is 
>                                   all sum at the end? 

If you think about building up from the simplest case:
f([]) = []
f(['a']) = f([]) + ['a'] = [] + ['a'] = ['a']

Now f(['a', 'b']) is going to be:
f(['b']) + ['a']
= ['b'] + ['a']
= ['b', 'a']

Similarly, for f(['a', 'b', 'c']), that will be:
f(['b', 'c']) + ['a']

Of course, if you want to do this you can always use list.reverse() but I
guess you're trying to get a handle on recursion rather than just reverse a
list.  I find thinking up from the base case helps when trying to
understand recursive code but when writing it, I tend to work the other way
around.


-- 
I'm at CAMbridge, not SPAMbridge



More information about the Python-list mailing list