sum() requires number, not simply __add__
duncan.booth at invalid.invalid
Fri Feb 24 12:40:10 CET 2012
Stefan Behnel <stefan_ml at behnel.de> wrote:
> I know that you just meant this as an example, but it's worth
> mentioning in this context that it's not exactly efficient to "sum up"
> lists this way because there is a lot of copying involved. Each adding
> of two lists creates a third one and copies all elements into it. So
> it eats a lot of time and space.
If you search back through this group far enough you can find an
alternative implementation of sum that I suggested which doesn't have the
same performance problem with lists or strings and also improves the
accuracy of the result with floats.
In effect what it does is instead of:
(((((a + b) + c) + d) + e) + f)
it calculates the sum as:
((a + b) + (c + d)) + (e + f)
i.e. in as balanced a manner as it can given that it still has to work from
left to right.
Of course that could still change the final result for some user defined
types and never having converted my code to C I have no idea whether or not
the performance for the intended case would be competitive with the builtin
sum though I don't see why it wouldn't be.
Duncan Booth http://kupuguy.blogspot.com
More information about the Python-list