Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sum of 1-100
#1
Hi,

I came across this and was wondering about the mechanics:

>>> x = 0
>>> r = range(1, 101)
>>> for n in r:
...     x = n + x
... 
>>> x
5050
Comparing it to this though (which I somewhat understand), I'm not getting much of a sense of what's going on:
>>> x = 0
>>> r = range(1, 101)
>>> for n in r:
...     y = n + x
... 
>>> y
100

Thanks

-----

I got it! I figured I may as well answer my own question. The key is in understanding the true nature of the second example. In the first iteration, y = 1; in the second, y = 2; and so on, and what you end up 'keeping' is the final iteration, where y = 100. Now apply that same logic to the first example: in the first iteration, x = 1; but in the second, x = 3; and in the third, x = 5; and so on, until you reach the final iteration where x = 5050 -- and that is the iteration you 'keep'.
Reply
#2
hi,

if you looks the first code, every time you iterate a new 'n' in 'r', it s added to 'x' and 'x' change after each iteration.
in the second one, for each iteration, you give a new value for 'y' which is the value of 'n' plus the value of 'x' and x=0.
I hope that will be helpful
Reply
#3
Some other possibilities about getting sum of numbers in range 1 - 100.

You can slightly modify you code by using +=:

>>> x = 0
>>> r = range(1, 101)
>>> for n in r:
...     x += n
...
>>> x
5050
You can iterate directly over range:

>>> x = 0
>>> for n in range(1, 101):
...     x += n
...
>>> x
5050
You can present this code as one-liner:

>>> sum(x for x in range(1, 101))
5050
You can get rid of comprehension and just sum range:

>>> sum(range(1, 101))
5050
However, all above represent brute-force approach. In case of really big numbers 'the right' way to approach this problem is to use triangular numbers:

>>> (100 * (100 + 1)) / 2
5050.0
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020