Python - sum of numbers

I am trying to sum all numbers to a range, with all numbers 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 fine, however, due to nested loops, if the limit is too large, it will take a long time to calculate the sums.

Is there a way to do this without a nested loop?

(This is simply a simplification of what I need to do to solve the ProjectEuler problem. It involves getting the sum of all the bountiful numbers.)

+3
source share
3 answers
[x + y for x in xrange(limit + 1) for y in xrange(x + 1)]

It does the same amount of calculations anyway, but will do it about twice as fast as the for loop.

from itertools import combinations

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

. , .

, , xrange(2*n + 2) , , .

:

 [x + y for x in set set1 for y in set2]
+2

, .

, limit**2.

- , , .

: "- " - , , , .

?

, @aaron, - ( , ), , , .

,

.

, ; -).

, 23, : , . , , , .

+1

, .

, :

[x + y x (1, + 1) y (1, + 1)]

0

Source: https://habr.com/ru/post/1759452/


All Articles