Sum of 1-100 - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Sum of 1-100 (/thread-16498.html) |
Sum of 1-100 - ClassicalSoul - Mar-02-2019 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 5050Comparing 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'. RE: Sum of 1-100 - Scorpio - Mar-02-2019 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 RE: Sum of 1-100 - perfringo - Mar-02-2019 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 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 |