+ 1

all numbers from 1 - 100

How to write sum of all numbers from 1 - 100 in python

24th Apr 2017, 9:13 PM
Fade Made
Fade Made - avatar
5 ответов
+ 19
print(sum(range(1, 101)))
24th Apr 2017, 9:16 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 6
sum = 0 for i in range(1,101): sum+=i print(sum)
24th Apr 2017, 9:18 PM
Mario L.
Mario L. - avatar
+ 3
Every once in a while I pop up to verify timings. I had tested several sums--but not Gauss. To avoid confusion I am not linking my test; I am just supporting the 'optimal' vs. easy-to-understand discussion to keep in the back of our minds. 100,000 tests: timeUsed : basic strategy 1.06 : Mario L (easy to read) 0.32 : Kuba (Python has it) 0.05 : Klaus-Dieter...(Gauss had it)
26th Apr 2017, 4:10 AM
Kirk Schafer
Kirk Schafer - avatar
+ 2
before using fast solutions, someone who is still at the beginning of learning should use easy to follow solutions which are often really slow, but you can go through each step easily. afterwards you can shorten the code or find algorithms.
25th Apr 2017, 5:41 AM
Mario L.
Mario L. - avatar
+ 1
Kuba's answer is the the obvious solution and Mario's solution is fine too, but slower. However, if you're just summing over a range from 1 to N with an increment of 1, there is third approach that SIGNIFICANTLY beats both in terms of speed: def rangesum(upper): '''calculate the sum of range(1, upper) including upper using the Gauss formula''' return upper * (upper + 1) / 2 Note that I didn't invent this. It was C. F. Gauss around 1786 - at the age of nine.
25th Apr 2017, 4:34 AM
Klaus-Dieter Warzecha
Klaus-Dieter Warzecha - avatar