reduce versus recursion? what am I missing...
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-tup)
> 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
l = list(tup[1:])
l = abs(tup-tup)
> 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)
> # output:
> #--- test:
> #recursion: 2 ( appears not to actually be recursing more than 1
> #reduce: 5
More information about the Python-list