Last active
August 21, 2021 03:35
-
-
Save onelharrison/a8f930af2c12da493b2f331b25ca3a99 to your computer and use it in GitHub Desktop.
Python recipe for generating subsets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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