lambda (and reduce) are valuable

bonono at gmail.com bonono at gmail.com
Sat Dec 10 04:34:34 EST 2005


Peter Otten wrote:
> Alan aka David Isaac wrote:
>
> >>> #evaluate polynomial (coefs) at x using Horner's rule
> >>> def horner(coefs,x): return reduce(lambda a1,a2: a1*x+a2,coefs)
>
> > It just cannot get simpler or more expressive.
>
> But is it correct?
>
> >>> a0, a1, a2 = 1, 2, 3
> >>> x = 2
> >>> a0 + x*(a1 + x*(a2))
> 17
> >>> def horner(coefs, x): return reduce(lambda a1, a2: a1*x + a2, coefs)
> ...
> >>> horner([a0, a1, a2], x)
> 11
>
> Are we merely employing different conventions for the order of coefficients
> or is that simple and expressive lambda/reduce stuff obscuring an error?
>
I think horner needs the coefs be "reversed", comparing with how we
like to express polynomial in general, that is how I read those math
formulas about horner anyway.




More information about the Python-list mailing list