[Numpy-discussion] Simple multi-arg wrapper for dot()

Bill Baxter wbaxter@gmail....
Sat Mar 24 15:51:41 CDT 2007


On 3/25/07, Alan G Isaac <aisaac@american.edu> wrote:
> On Sun, 25 Mar 2007, Bill Baxter apparently wrote:
> > So if one just
> > changes the example to
> >   reduce(lambda s, a: s * a.myattr, data, 1)
> > How does one write that in a simplified way using generator
> > expressions without calling on reduce?
>
>
> Eliminating the expressiveness of ``reduce`` has in my
> opinion never been publically justified.

Though the post on Guido's blog got lots of people jumping on the
witch-burning bandwagon for getting rid of reduce().  I think I saw
"good riddance" more than once.  On the other hand slightly fewer
people people said "hey I use that!"

>
> E.g., ::
>
>     #evaluate polynomial (coefs=[an,...,a0]) at x
>     # using Horner's rule
>     def horner(coefs, x):
>         return reduce(lambda a1,a0: a1*x+a0, coefs)
>
> I suspect that ``reduce`` remains in danger only because the
> math community has been too quiet.

To be fair, the alternative is

def horner2(coefs, x):
   ret = 0
   for a in coefs:  ret = ret*x + a
   return ret

Which, though more typing, isn't really any harder or easier to read in my mind.
But there is a difference in timings:

In [107]: t1 = timeit.Timer('horner([4,3,2,1],2)','from __main__ import horner')
In [108]: t2 = timeit.Timer('horner2([4,3,2,1],2)','from __main__
import horner2')
In [111]: t1.timeit(), t2.timeit()
Out[111]: (2.463477341393947, 1.1736731903077064)

The explicit loop runs about twice as fast in this case.

I think it's fine for filter()/reduce()/map() to be taken out of
builtins and moved to a standard module, but it's not clear that
that's what they're going to do.  That py3K web page just says "remove
reduce()... done".

--bb


More information about the Numpy-discussion mailing list