A powerset is the set of all subsets for a given set.
For a given set S: the powerset P(S) the set of all subsets of that set S.
- P(S) = {T: T ⊆ S) where T is a set.
Given a set with three elements {1, 2, 3}, the powerset P({1, 2, 3}) would contain the eight subsets of the set, including itself and the empty set:
- {∅, {1}, {2}, {3}, {1,2}, {1,3}, {2,3}, {1,2,3}}
For a set S of finite size n, the size of the powerset P(S) is 2n. The cardinality of S is always strictly less than the cardinality of P(S): the set of natural numbers N is countably infinite, but the set of the powerset of N is uncountable.
Algorithm to create a Powerset
Python offers itertools which can be used to create a powerset of a given set or list. Here is the documentation: https://docs.python.org/3/library/itertools.html#recipes
def powerset(s: set):
s = list(s)
ps = chain.from_iterable(combinations(s, r) for r in range(len(s) + 1))
return list(ps) # set(ps) also works
Here is a test run:
s = {1,2,3}
ps = powerset(s)
# ps = [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
There exists an iterative method to create a powerset. The size of the powerset grows exponentially and reaches over two billion for sets of size larger than 32. For a set S of size n:
- Create an initially empty list L which will eventually represent the powerset
- For each element, give it an index, ranging from 0 to n-1.
- Suppose we have {A, B, C}. Let the index of A be 0, B be 1, C be 2.
- Loop through all the numbers from 0 to 2n-1 and express each in binary form.
- The loop counter i goes from 0 (
000
in binary) to 7 (111
in binary).
- The loop counter i goes from 0 (
- Create a subset Ti based on the binary number, which contains the elements such that the binary digit position of the elements' index for i is 1.
- The ones digit is given position 0, the fours digit (third digit) is given position 2.
- When we have 0, the subset T0 is the empty set.
- When we have 5, the binary digits are
101
, the digits with position 2 and 0 are ones, and so the subset T5 is {A, C}.
- Add that subset to the original list L.