Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sum of 1-100
#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


Messages In This Thread
Sum of 1-100 - by ClassicalSoul - Mar-02-2019, 02:01 PM
RE: Sum of 1-100 - by Scorpio - Mar-02-2019, 02:15 PM
RE: Sum of 1-100 - by perfringo - Mar-02-2019, 05:17 PM

Forum Jump:

User Panel Messages

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