total = 0
for i in range(0, some upper bound):
total += i
Sorry if this is basic but I have a lot of these and they\'re taking up more room than is
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.
total = sum(range(upper))
or
total = upper * (upper - 1) / 2
The 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) / 2
If you are on Python 2.x, replace all range
with xrange
.
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):
public int sumUpToBoundary(def upper_bound){
return (upper_bound) * (upper_bound - 1) / 2;
}
public int sumBetween(def lower_bound, def upper_bound){
return sumUpToBoundary(upper_bound) - sumUpToBoundary(lower_bound);
}
public void someOtherMethod() {
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.