Praveen
Praveen

Reputation: 783

How to get Integer Combination Have Specific Sum and Specific Starting Element?

i need to find out combinations from an integer list which satisfies a condition that the combination sum is equal to some specific value. For example I have list [1,2,3,4] I need to find out all combinations have only two integer values and sum of that integers equal to 5. I tried it with itertools.combinations() and get all the combinations but how to include the sum condition to it . And i also need to know that how to specify the starting element of the combination. Example combination starting with 1 only. Is there any libraries exists and please tell me to find out the fastest combination finding methods

Upvotes: 1

Views: 281

Answers (2)

Ami Tavory
Ami Tavory

Reputation: 76297

IIUC, you can simply combine it with conditional list comprehension.

E.g.,

>>> [(i, j) for (i, j) in itertools.combinations([1,2,3,4], 2) if i + j == 5]
[(1, 4), (2, 3)]

or, the ones starting with 1 only

[(i, j) for (i, j) in itertools.combinations([1,2,3,4], 2) if i == 1]

(Of course, you can combine whatever conditionals you want.)

Upvotes: 1

Paweł Kordowski
Paweł Kordowski

Reputation: 2768

you can use filter

filter(lambda x: sum(x) == 5 and x[0] == 1, combinations([1, 2, 3, 4], 2))

Upvotes: 0

Related Questions