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


total = 0 in range(0, upper bound):     total += 

sorry if basic have lot of these , they're taking more room comfortable.

total = sum(range(upper)) 

or

total = upper * (upper - 1) / 2 

the first 1 python, second 1 gauss.

edit: when not starting @ zero:

total = sum(range(lower, upper)) 

or, again according gauss, same upper , substract same lower:

total = upper * (upper - 1) / 2 - lower * (lower - 1) / 2 

if on python 2.x, replace range xrange.


Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -