how to get all combinations of a set in python

One solution to obtain all possible combinations of a set in Python is to use the combinations function from the itertools module. This function returns an iterator that generates all possible combinations of a given iterable. Here's an example:

main.py
import itertools

my_set = {1, 2, 3}
combinations = []

for i in range(len(my_set) + 1):
    for subset in itertools.combinations(my_set, i):
        combinations.append(subset)

print(combinations)
199 chars
11 lines

In this example, the code generates all possible combinations of the set {1, 2, 3}, and stores them in a list named combinations. The outer loop iterates over all possible sizes of subsets (from 0 to the size of the original set), while the inner loop generates all possible combinations of the current size using the combinations function. The result is a list of tuples containing all possible subsets of the original set, including the empty set and the set itself.

gistlibby LogSnag