607 B
607 B
title, tags
| title | tags |
|---|---|
| powerset | math,list,advanced |
Returns the powerset of a given iterable.
- Use the
list()constructor to convert the given value to alist. - Use
range()andcombinations()to create a generator the returns all subsets. - Use
chain.from_iterable()and thelist()constructor to consume the generator and return a list.
from itertools import chain, combinations
def powerset(iterable):
s = list(iterable)
return list(chain.from_iterable(combinations(s, r) for r in range(len(s)+1)))
powerset([1, 2]) # [(), (1,), (2,), (1, 2)]