1

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

2 Answers 2

1

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.)

Sign up to request clarification or add additional context in comments.

Comments

0

you can use filter

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.