Files
30-seconds-of-code/python/s/powerset.md
Angelos Chalaris 5c913d20bd Reorganize snippets
2023-05-03 21:19:02 +03:00

678 B

title, type, language, tags, author, cover, dateModified
title type language tags author cover dateModified
Powerset snippet python
math
list
chalarangelo rock-climbing 2020-11-02T19:28:27+02:00

Returns the powerset of a given iterable.

  • Use list() to convert the given value to a list.
  • Use range() and itertools.combinations() to create a generator that returns all subsets.
  • Use itertools.chain.from_iterable() and list() 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)]