Sometimes, we want to get all subsets of a set (powerset) with Python.
In this article, we’ll look at how to get all subsets of a set (powerset) with Python.
How to get all subsets of a set (powerset) with Python?
To get all subsets of a set (powerset) with Python, we can use the chain.from_iterable
and combinations
functions.
For instance, we write:
from itertools import chain, combinations
def powerset(iterable):
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1))
p = list(powerset("abc"))
print(p)
We define the powerset
function that takes an iterable
object.
In the function, we convert the iterable
object to a list with list
.
Then we call chain.from_iterable
with the list of combinations of all the elements in s
.
We get all combinatins with r
going from 0 to range(len(s) + 1)
.
Each combination is stored in a tuple.
Therefore, p
is:
[(), ('a',), ('b',), ('c',), ('a', 'b'), ('a', 'c'), ('b', 'c'), ('a', 'b', 'c')]
Conclusion
To get all subsets of a set (powerset) with Python, we can use the chain.from_iterable
and combinations
functions.