Inefficient summing

Alexander Schmolck a.schmolck at gmail.com
Fri Oct 10 10:43:33 CEST 2008


beginner <zyzhu2000 at gmail.com> writes:

> On Oct 9, 3:53 pm, Alexander Schmolck <a.schmo... at gmail.com> wrote:
>> beginner <zyzhu2... at gmail.com> writes:
>> how about:
>>
>> ratio = (lambda c: c.real/c.imag)(sum(complex(r["F1"], r["F2"] for r in rec)))
>>
> Neat, but I will have a problem if I am dealing with three fields,
> right?

Sure but then how often do you want to take the ratio of 3 numbers? :) 

More seriously if you often find yourself doing similar operations and are
(legimately) worried about performance, numpy and pytables might be worth a
look. By "legitimately" I mean that I wouldn't be bothered by iterating twice
over rec; it doesn't affect the algorithmic complexity at all and I woudn't be
surprised if sum(imap(itemgetter("F1"),rec))/sum(imap(itemgetter("F2"),rec))
weren't faster than the explicit loop version for the cases you care about
(timeit will tell you). You're right that you loose some generality in not
being able to deal with arbitrary iterables in that case though.

'as



More information about the Python-list mailing list