Best way to make a weighted sum

Jorge Godoy godoy at metalab.unc.edu
Tue Apr 8 18:01:13 EDT 2003


Lulu of the Lotus-Eaters <mertz at gnosis.cx> writes:

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

Thanks.


This is also the kind of thing I was looking for. The reduce() and
zip() functions are very interesting. And the operator module was
already being used in other parts of the code, so why not here, in
this class? :-) 

-- 
Godoy.      <godoy at metalab.unc.edu>

	"... The name of the song is called 'Haddocks' Eyes'!"
	"Oh, that's the name of the song, is it?" Alice said, trying to
feel interested.
	"No, you don't understand," the Knight said, looking a little
vexed.  "That's what the name is called.  The name really is, 'The Aged
Aged Man.'"
	"Then I ought to have said "That's what the song is called'?"
Alice corrected herself.
	"No, you oughtn't:  that's quite another thing!  The song is
called 'Ways and Means':  but that's only what it is called you know!"
	"Well, what is the song then?" said Alice, who was by this time
completely bewildered.
	"I was coming to that," the Knight said.  "The song really is
"A-sitting on a Gate":  and the tune's my own invention."
		-- Lewis Carroll, "Through the Looking Glass"




More information about the Python-list mailing list