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.
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))
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')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With