Best way to make a weighted sum

Lulu of the Lotus-Eaters mertz at gnosis.cx
Tue Apr 8 16:36:29 EDT 2003


Jorge Godoy <godoy at metalab.unc.edu> wrote previously:
|    def CalculaSoma(self):
|        ie = self.ie
|        iter = len(ie)
|        for i in ie:
|            produto = i * self.pesos[iter]
|            self.soma = self.soma + produto
|            iter = iter - 1
|I don't know if I got it in the most pythonic way in my code.

Looks fine.  You could be somewhat more concise with:

    from operator import mul, add
    amts, weights = pesos.keys(), pesos.items()
    sum = reduce(add, map(mul, amts, weights))/reduce(add, weights)

I'll leave it to a native speaker to translate my var names to
Portuguese.

Yours, Lulu...

--
 mertz@   _/_/_/_/_/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY:_/_/_/_/ v i
gnosis  _/_/                    Postmodern Enterprises         _/_/  s r
.cx    _/_/  MAKERS OF CHAOS....                              _/_/   i u
      _/_/_/_/_/ LOOK FOR IT IN A NEIGHBORHOOD NEAR YOU_/_/_/_/_/    g s






More information about the Python-list mailing list