computing a weighted sum

Raymond Hettinger vze4rx4y at verizon.net
Thu Mar 17 03:11:11 EST 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)))
> 90.0

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))


Raymond Hettinger







More information about the Python-list mailing list