Is There A Faster Way To Sum Up An Arithmetic Sequence Of Numbers In Python?
Solution 1:
total = sum(range(upper))
or
total = upper * (upper - 1) / 2The first one is Python, the second one Gauss.
EDIT: When not starting at zero:
total = sum(range(lower, upper))
or, again according to Gauss, do the same with upper and substract the same for lower:
total = upper * (upper - 1) / 2 - lower * (lower - 1) / 2If you are on Python 2.x, replace all range with xrange.
Solution 2:
total = some_upper_bound * (some_upper_bound -1) / 2
if lower_bound != 0:
total = (some_upper_bound - lower_bound) * (some_upper_bound + lower_bound - 1) / 2
Update: I would've deleted my answer as it is practically an exact copy of part of the accepted answer (although I answered independently). There is, however, one - very small, but theoretically interesting improvement when lower_bound is involved: my answer contains only two multiplications / divisions (which are relatively more expensive than additions/subtractions) while the other answer contains four.
Solution 3:
To expand on eumiro. You may want to write a method that encapsulates the Gauss method for clarity. I would suggest something like this (written in Groovy because I don't know Python syntax):
publicintsumUpToBoundary(def upper_bound){
return (upper_bound) * (upper_bound - 1) / 2;
}
publicintsumBetween(def lower_bound, def upper_bound){
return sumUpToBoundary(upper_bound) - sumUpToBoundary(lower_bound);
}
publicvoidsomeOtherMethod() {
int total = sumUpToBoundary(some_upper_bound);
int total2 = sumBetween(some_lower_bound, some_upper_bound);
}
UPDATE: @mspy noted that my method signatures weren't in the style of Python. I've updated the example to groovy which supports somewhat more Python-like syntax.
Post a Comment for "Is There A Faster Way To Sum Up An Arithmetic Sequence Of Numbers In Python?"