0

I have a list of numbers and I have to find a way to print a sub-list where the sum of its elements is the same as the sum of all the elements of the original list. For example [5,6,8,6,6,-12] and the result should be [5,6,8]

1 Answers1

1

Method using itertools.combinations. Note that this brute forces all combinations so is applicable for small list sizes like the example given.

>>> numbers = [5,6,8,6,6,-12]
>>> for i in range(len(numbers)):
...     print([combo for combo in itertools.combinations(numbers, i) if sum(combo) == sum(numbers)])

output:

[]
[]
[]
[(5, 6, 8), (5, 8, 6), (5, 8, 6)]
[]
[]

You can then decide what to do with the resulting lists.


If you want to remove duplicate combinations from the list you can use itertools.groupby as shown here: https://stackoverflow.com/a/2213973/15981783

ChrisOram
  • 1,254
  • 1
  • 5
  • 17