+ 1
all numbers from 1 - 100
How to write sum of all numbers from 1 - 100 in python
5 Respuestas
+ 19
print(sum(range(1, 101)))
+ 6
sum = 0
for i in range(1,101):
sum+=i
print(sum)
+ 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)
+ 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.
+ 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.