recursion gotcha?

Arnaud Delobelle arnodel at googlemail.com
Sun Sep 14 05:31:16 EDT 2008


On Sep 14, 9:44 am, "Marco Bizzarri" <marco.bizza... at gmail.com> wrote:
> On Sun, Sep 14, 2008 at 10:08 AM, Marco Bizzarri
>
>
>
> <marco.bizza... at gmail.com> wrote:
> > On Sun, Sep 14, 2008 at 10:01 AM, cnb <circularf... at yahoo.se> wrote:
> >> this recursive definition of sum thrumped me, is this some sort of
> >> gotcha or am I just braindead today?
> >> and yes i know this is easy a a for x in xs acc += x or just using the
> >> builtin.
>
> >> def suma(xs, acc=0):
> >>        if len(xs) == 0:
> >>                acc
> >>        else:
> >>                suma(xs[1:], acc+xs[0])
>
> > You're just missing the "return" statements?
>
> > def suma(xs, acc=0):
> >       if len(xs) == 0:
> >              return acc
> >       else:
> >              return suma(xs[1:], acc+xs[0])
>
> Besides: you can avoid the "acc" parameter:
>
> def suma(xs):
>     if len(xs) == 0:
>         return 0
>     else:
>         return xs[0] + suma(xs[1:])
>

I think the OP tried to make it tail-recursive, which of course has no
benefit in Python.  In fact it looks like a Scheme implementation of
sum translated literally to Python.

In Python this algorithm is expressed naturally as:

def suma(xs):
    acc = 0
    for x in xs:
        acc += x
    return acc

--
Arnaud




More information about the Python-list mailing list