Is there a faster way to sum up an arithmetic sequence of numbers in Python?

后端 未结 3 872
猫巷女王i
猫巷女王i 2021-01-26 18:15
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

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-26 18:35

    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.

提交回复
热议问题