Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a list of sets of atoms

Tags:

python

set

Say I have an array of atoms like this:

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

(the length may 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 it easily in python?

Maybe it's very easy to do, but I'm not getting it myself.
Thank you.

like image 328
Nuno Avatar asked Apr 28 '12 22:04

Nuno


2 Answers

That 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))
like image 120
senderle Avatar answered Oct 06 '22 06:10

senderle


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 yields:

[('a',), ('b',), ('c',), ('a', 'b'), ('a', 'c'), ('b', 'c'), ('a', 'b', 'c')]
like image 42
Joel Cornett Avatar answered Oct 06 '22 06:10

Joel Cornett