How? – How to use this package¶
The package provides a single function, subsets()
, which returns a collections.abc.Generator
for the subsets of of collection
.
- powerset_generator.subsets(collection)¶
Generates all the subsets of the powerset of collection.
- Parameters:
collection (
Collection
[TypeVar
(T
, bound=Hashable
)]) – The collection you want the subsets of- Return type:
Power sets¶
The power set of a collections is the set of all subsets of the collection.
The power set includes the empty set.
The power set includes a set of all members of the collections. That is, it is not limited to the proper subsets of the collection.
If the collection has N unique elements, the power set will have 2^N` elements.
Usage notes¶
This this fuction generates sets irrespective of the type of its input. That is, given a list, it will yield sets.
In the current version there is no enforcement of the type hinting that members of the input collection all be of the same type. But do not rely on this lax behavior.
Example:
from powerset_generator import subsets a_list: list[str] = ["one", "two", "three"] for element in subsets(s): print(element)
produces:
set() {'one'} {'three'} {'two'} {'one', 'three'} {'one', 'two'} {'three', 'two'} {'one', 'three', 'two'}
Exceptions¶
powerset does not explicitly raise any exceptions on its own, but if its argument is not Collection[Hashable] some of the functions it calls internally are likely to raise a TypeError.
Additional notes¶
The number of subsets of a collection with N unique elements is \(2^N\). You can compute that with
import collections
N = 20
collection = list(range(N))
2 ** len(collections.Counter(collection))
1048576
You can work around the limitation that the members of the collections.abc.Collection
must be collections.abc.Hashable
by using dictionary keys.
For example, if your collection is a dictionary,
you can just generate the powerset of the keys of your dictionary.