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

Praveen
  • 733
  • 2
  • 7
  • 16

2 Answers2

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

Community
  • 1
  • 1
Ami Tavory
  • 74,578
  • 11
  • 141
  • 185
0

you can use filter

filter(lambda x: sum(x) == 5 and x[0] == 1, combinations([1, 2, 3, 4], 2))
Paweł Kordowski
  • 2,688
  • 1
  • 14
  • 21