Create atom set list

Let's say I have such an array of atoms:

['a', 'b', 'c'] 

(length can be any)

And I want to create a list of sets that can be made with them:

 [ ['a'], ['b'], ['c'], ['a', 'b'], ['a', 'c'], ['b', 'c'], ['a', 'b', 'c'] ] 

Is it possible to do this in python?

It may be very easy to do, but I do not get it myself.
Thanks.

+7
source share
3 answers

This sounds to me like powerset :

 def powerset(iterable): "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" s = list(iterable) return chain.from_iterable(combinations(s, r) for r in range(len(s)+1)) 
+15
source

Easy. Use itertools.combinations() :

 from itertools import combinations atom = list('abc') combs = [i for j in range(1, len(atom) + 1) for i in combinations(atom, j)] 

which gives:

 [('a',), ('b',), ('c',), ('a', 'b'), ('a', 'c'), ('b', 'c'), ('a', 'b', 'c')] 
+4
source

You can also do:

 from itertools import product masks = [p for p in product([0, 1], repeat=len(data))] combs = [[x for i, x in enumerate(data) if mask[i]] for mask in masks] 
0
source

All Articles