Skip to content Skip to sidebar Skip to footer

Is There A Faster Way To Sum Up An Arithmetic Sequence Of Numbers In Python?

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 comfortable.

Solution 1:

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.

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?"