Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Sum of numbers

I am trying to sum all the numbers up to a range, with all the numbers up to the same range.

I am using python:

limit = 10
sums = []
for x in range(1,limit+1):
    for y in range(1,limit+1):
        sums.append(x+y)

This works just fine, however, because of the nested loops, if the limit is too big it will take a lot of time to compute the sums.

Is there any way of doing this without a nested loop?

(This is just a simplification of something that I need to do to solve a ProjectEuler problem. It involves obtaining the sum of all abundant numbers.)

like image 452
AlexBrand Avatar asked Aug 16 '26 14:08

AlexBrand


1 Answers

[x + y for x in xrange(limit + 1) for y in xrange(x + 1)]

This still performs just as many calculations but will do it about twice as fast as a for loop.

from itertools import combinations

(a + b for a, b in combinations(xrange(n + 1, 2)))

This avoids a lot of duplicate sums. I don't know if you want to keep track of those or not.

If you just want every sum with no representation of how you got it then xrange(2*n + 2) gives you what you want with no duplicates or looping at all.

In response to question:

 [x + y for x in set set1 for y in set2]
like image 197
aaronasterling Avatar answered Aug 18 '26 03:08

aaronasterling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!