reduce versus recursion? what am I missing...

Tim Hochberg tim.hochberg at ieee.org
Fri Apr 7 18:35:31 CEST 2000


> # I am trying to figure out why function d (recursive) and e (reduce)
> # DON'T do the SAME thing:
>
> def d(*tup):
>     "why doesn't this work?"
>     if len(tup)>1:
>         return d(tup[1:])+abs(tup[0]-tup[1])
>     else:
>         return 0

There are two problems here. First, you need to call apply(d, x) here
instead of d(x), on the second call, the function sees a singleton tuple
that looks like (tup[1:],) where tup is the original tuple.

Second, the recursive problem is not doing the same thing as the reduce: the
first element of the tuple passed down the chain needs to be made equal to
the difference. I believe the following does what you want, although it's a
little akward.

def d(*tup):
    if len(tup)>1:
        l = list(tup[1:])
        l[0] = abs(tup[0]-tup[1])
        return apply(d,l)
    else:
        return tup[0]

> l = (1,3,5,7,9)
>
> def e(*tup):
>     "it works"
>     return reduce(lambda x,y:abs(x-y),tup,0)
>
> print "--- test:"
> print "recursion: ",apply(d,l)
> print "reduce:    ",apply(e,l)
>
> #---
> #Warren
> #
> # output:
> #--- test:
> #recursion:  2     ( appears not to actually be recursing more than 1
> level!!!???)
> #reduce:     5
>
>
>





More information about the Python-list mailing list