computing a weighted sum
vze4rx4y at verizon.net
Thu Mar 17 09:11:11 CET 2005
[Christos TZOTZIOY Georgiou]
> 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)))
Gack! starmap() is only for situations where the data is already in tuple form.
If it inputs are already distinct, imap() is the preferred form.
FWIW, the answer was already in the docs (itertools recipes):
def dotproduct(vec1, vec2):
return sum(imap(operator.mul, vec1, vec2))
More information about the Python-list