Skip to content

Instantly share code, notes, and snippets.

@onelharrison
Last active August 21, 2021 03:35
Show Gist options
  • Save onelharrison/a8f930af2c12da493b2f331b25ca3a99 to your computer and use it in GitHub Desktop.
Save onelharrison/a8f930af2c12da493b2f331b25ca3a99 to your computer and use it in GitHub Desktop.
Python recipe for generating subsets
from itertools import chain, combinations
from typing import Collection, Iterable, Optional
def subsets(
collection: Collection, min_size: int = 0, max_size: Optional[int] = None
) -> Iterable:
"""Produce all the subsets of `collection` with cardinalities between
`min_size` and `max_size` (inclusive)."""
min_size = max(0, min_size)
max_size = max_size if max_size is not None else len(collection)
return chain(
*{map(set, combinations(collection, r)) for r in range(min_size, max_size + 1)}
)
if __name__ == "__main__":
fruits = ["apple", "banana", "orange", "mango", "pineapple"]
fruits_powerset = list(subsets(fruits))
fruits_subsets_1to3 = list(subsets(fruits, min_size=1, max_size=3))
print(f"Power set of {fruits}: {fruits_powerset}", end="\n\n")
print(f"Subsets of {fruits} of size 1 to 3: {fruits_subsets_1to3}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment