-1

I tried this

import itertools
a=[10, 1 ,2, 7, 6, 1, 5]
b=[]
for i in range(len(a)):
    for s in itertools.combinations(a,i):
        if s not in b:
            b.append(s)
print(b)

I am getting desired output in form of tuple. I want output as below:

[[10],[1],...[10,1],...[10,1,2]....]
Vasilis G.
  • 7,556
  • 4
  • 19
  • 29
Abhi
  • 1,127
  • 1
  • 12
  • 25

1 Answers1

2

Most functions in itertools produce tuples, but the good news is that a tuple is an iterable, and you can use list(..) with an iterable to convert the iterable to a list.

We can thus for example map the results of the itertools, like:

from itertools import combinations

a=[10, 1 ,2, 7, 6, 1, 5]
b=[]
for i in range(len(a)):
    for s in map(list, combinations(a,i)):
        if s not in b:
            b.append(s)
print(b)

But nevertheless this is still not a good idea. A membership check of a list, runs in linear time. Since there are an exponential number of combinations, this means that it will start running in O((n!)2) time, with n the number of elements, which is typically very slow.

A faster way to do this, is using a set concurrently, that stores the elements, and then each time check membership of the tuple (a set can not contain lists, since lists are unhashable), in case the membership fails, we add it to b as a list:

from itertools import combinations

a=[10, 1 ,2, 7, 6, 1, 5]
b=[]
seen = set()

for i in range(len(a)):
    for s in combinations(a,i):
        if s not in seen:
            seen.add(s)
            b.append(list(s))
print(b)
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555