computing a weighted sum

Christos TZOTZIOY Georgiou tzot at sil-tec.gr
Wed Mar 16 11:08:14 EST 2005


On 16 Mar 2005 06:49:09 -0800, rumours say that andreif at mail.dntis.ro might have
written:

>Suppose I have a list of n floats x and a list of n floats w and I want
>to compute x[0]*w[0] + .. + x[n-1]*w[n-1].
>
>Is there some elegant expression (perhaps using lambda) to have it done
>in one statement ? As in :
>     y = lambda x,w : ...
>
>I ask because the way I am doing it now :
>      y = 0
>      for i in range(0,n): y += x[i]*w[i]
>
>doesn't seem very pythonic :)

Your method seems to be the one closest to what's generally considered as
pythonic.

Anyway, a functional equivalent:

.>> from itertools import starmap, izip
.>> import operator
.>> x= [1,2,3,4]
.>> w=[3.0, 6.0, 9.0, 12.0]
.>> sum(starmap(operator.mul, izip(x,w)))
90.0
.>>
-- 
TZOTZIOY, I speak England very best.
"Be strict when sending and tolerant when receiving." (from RFC1958)
I really should keep that in mind when talking with people, actually...



More information about the Python-list mailing list