What is a good implementation of Power Set algorithm?
Recently I needed this algorithm for building a solver for my puzzle game. Generally, the solver should try strategies (sets of turns, the possible turns Power Set) and find the strategy that forms a solution.
I found out, that the naive implementation shown at Wikipedia page, as well as one from js-combinatorics
library does not provide the stable order of items in generated subsets.
Also, the naive approach that utilise the bijection of the set to the natural numbers set and followed binary representation, is bounded by the size of the source set.
This limitation naturally occurs from the fact that internally the mentioned library uses 32-bit integer value for generating subsets.
Use the implementation fromt the itertools recipes:
from itertools import chain, combinations
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))
print(*powerset([1,2,3]))
Output:
() (1,) (2,) (3,) (1, 2) (1, 3) (2, 3) (1, 2, 3)
It produces tuples - but you can convert them as you like. It looks also much shorter then your solution...