Efficient way to sum a product of numbers...

vsoler vicente.soler at gmail.com
Mon Aug 31 12:43:45 EDT 2009


On Aug 31, 6:30 pm, Tim Chase <python.l... at tim.thechases.com> wrote:
> > After simplifying my problem, I can say that I want to get the sum of
> > the product of two culumns:
>
> > Say
> >          m= [[ 'a', 1], [ 'b', 2],[ 'a', 3]]
>
> assuming you meant ['c', 3] here...    ^>          r={'a':4, 'b':5, 'c':6}
>
> > What I need is the calculation
>
> >          1*4 + 2*5 + 3*4 = 4 + 10 + 12 = 26
>
> and you mean "3*6" here instead of "3*4", which is 18 instead of
> 12, making the whole sum 4+10+18=32
>
> Then it sounds like you could do something like
>
>   result = sum(v * r[k] for k,v in m)
>
> where "m" is any arbitrary iterable of tuples.  If the keys (the
> letters) aren't guaranteed to be in "r", then you can use
> defaults (in this case "0", but could just as likely be "1"
> depending on your intent):
>
>   result = sum(v * r.get(k,0) for k,v in m)
>
> If the conditions above don't hold, you'll have to introduce me
> to your new math. ;-)
>
> -tkc

Hello Tim,

There is no mistake in my original post, so I really meant [ 'a', 3]

Imagine that m contains time sheets of suppliers

   supplier 'a' has worked for you 1 hour
   supplier 'b' has worked for you 2 hour
   supplier 'a' has worked for you 3 hour

Now

   supplier 'a' charges $4 per hour
   supplier 'b' charges $5 per hour
   supplier 'c' charges $6 per hour

I want to know how much I will be charged this month by my pannel of
suppliers.

   1*4 + 2*5 + 3*4 = 4 + 10 + 12 = 26

This is what I am after.
I expect all my suppliers to have handed me in advance the per hour
fee. If at least one hasn't, I must know that the result is undefined.

Hope this helps


Vicente Soler



More information about the Python-list mailing list