Inefficient summing
bearophileHUGS at lycos.com
bearophileHUGS at lycos.com
Wed Oct 8 17:22:41 EDT 2008
beginner:
> I can of course use an old-fashioned loop. This is more readable, but
> also more verbose.
> What is the best way, I wonder?
In such situation the old loop seems the best solution. Short code is
good only when it doesn't make the code too much slow/difficult to
understand. Keeping the code quite readable is very important. So I
think a simple solution is the best in this situation. The following
code can be understood quickly:
records = [{"F1": 1, "F2": 2}, {"F1": 3, "F2": 4}]
f1sum, f2sum = 0, 0
for rec in records:
f1sum += rec["F1"]
f2sum += rec["F2"]
ratio = f1sum / float(f2sum)
print ratio
Output:
0.666666666667
Note that I allowed myself to use this line of code:
f1sum, f2sum = 0, 0
because the two values on the right are equal, so you don't need one
bit of brain to understand where each value goes :-)
You can of course generalize the code in various ways, for example:
keys = ["F1", "F2"]
totals = [0] * len(keys)
for rec in records:
for i, key in enumerate(keys):
totals[i] += rec[key]
ratio = totals[0] / float(totals[1])
print ratio
But that already smells of over-engineering. Generally it's better to
use the simpler solution that works in all your cases at a speed that
is acceptable for you (my variant of the KISS principle).
Bye,
bearophile
More information about the Python-list
mailing list