-4

I am trying to loop thrue a list in python of integers, finding all uniqe combinations but if one element has been used from the list to create a combination the element can not be used again.

import itertools
import collections

list = [1, 3, 6, 8, 10, 13, 18, 25, 40, 60]
result_comb = []
result_val = []

for L in range(len(list) + 1):
    for subset in itertools.combinations(list, L):
        result_comb.append(subset)
        result_val.append(sum(subset))

Here i get the combinations and its values, but the same elements has been used alot of times.

petezurich
  • 9,280
  • 9
  • 43
  • 57
Spirarn
  • 1
  • 3
  • https://stackoverflow.com/a/5898031/10968621, Is this what you want? – iamjaydev Nov 15 '22 at 07:18
  • Lets say list is `[1, 3, 6]` and the output should be `[(), (1,), (3,), (6,), (1, 3), (1, 6), (3, 6), (1, 3, 6)]` ? – Faisal Nazik Nov 15 '22 at 07:26
  • @FaisalNazik no, if the list is [1, 3, 6] then theputput should be [(), (1,) (3,), (6,)] or [(), (1, 3), (6)] if the elemetns has been used it cannot be used again. – Spirarn Nov 15 '22 at 07:39

1 Answers1

1

I find the easy way to do this is to run through the binary numbers. 1 means the element is included, 0 means it isn't.

lst = [1, 3, 6, 8, 10, 13, 18, 25, 40, 60]

def makecombos(lst):
    for i in range(2**len(lst)):
        result = [lst[bit] 
            for bit in range(len(lst))
            if i & (1<<bit)
        ]
        yield result

for r in makecombos(lst):
    print(r)

Output:

[]
[1]
[3]
[1, 3]
[6]
[1, 6]
[3, 6]
[1, 3, 6]
[8]
...
[1, 8, 10, 13, 18, 25, 40, 60]
[3, 8, 10, 13, 18, 25, 40, 60]
[1, 3, 8, 10, 13, 18, 25, 40, 60]
[6, 8, 10, 13, 18, 25, 40, 60]
[1, 6, 8, 10, 13, 18, 25, 40, 60]
[3, 6, 8, 10, 13, 18, 25, 40, 60]
[1, 3, 6, 8, 10, 13, 18, 25, 40, 60]
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30