Skip to content
This repository was archived by the owner on May 7, 2023. It is now read-only.

Files

Latest commit

 

History

History
26 lines (21 loc) · 661 Bytes

powerset.md

File metadata and controls

26 lines (21 loc) · 661 Bytes
title type tags author cover dateModified
Powerset
snippet
math
list
chalarangelo
rock-climbing
2020-11-02 19:28:27 +0200

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)]