Mar-02-2019, 05:17 PM
Some other possibilities about getting sum of numbers in range 1 - 100.
You can slightly modify you code by using +=:
You can slightly modify you code by using +=:
>>> x = 0 >>> r = range(1, 101) >>> for n in r: ... x += n ... >>> x 5050You can iterate directly over range:
>>> x = 0 >>> for n in range(1, 101): ... x += n ... >>> x 5050You can present this code as one-liner:
>>> sum(x for x in range(1, 101)) 5050You can get rid of comprehension and just sum range:
>>> sum(range(1, 101)) 5050However, 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.
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.