Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding a sum of X numbers within a list (Python)

i'm trying to find a combination for a sum inside a list of integers.

the amount of numbers that contain the sum is limited by a variable, so for example in the list -

[5,2,3,9,1], i would like to find the sum of 10, with only 2 numbers.

so that the program would print out [9,1].

I'm new to python, is there an easy way of doing it?

thank you.

like image 410
Krypton Avatar asked Oct 25 '13 20:10

Krypton


People also ask

How do you sum elements in a list?

Sum Of Elements In A List Using The sum() Function. Python also provides us with an inbuilt sum() function to calculate the sum of the elements in any collection object. The sum() function accepts an iterable object such as list, tuple, or set and returns the sum of the elements in the object.

How do you sum a nested list in Python?

We can find sum of each column of the given nested list using zip function of python enclosing it within list comprehension. Another approach is to use map(). We apply the sum function to each element in a column and find sum of each column accordingly.


1 Answers

from itertools import combinations

l = [5,2,3,9,1]

for var in combinations(l, 2):
    if var[0] + var[1] == 10:
        print var[0], var[1]

Combinations create all possible combinations of tuples from an iterable object (an object you can loop over). Let me demonstrate:

>>> [var for var in combinations([1,2,3,4,5], 2)]
[(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]
>>> [var for var in combinations([1,2,3,4,5], 3)]
[(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5), (1, 4, 5), (2, 3, 4), (2, 3, 5), (2, 4, 5), (3, 4, 5)]
like image 59
Games Brainiac Avatar answered Oct 13 '22 00:10

Games Brainiac