how to get distinct combinations of a set in python

You can use the combinations() function from the itertools module to generate all possible combinations of a set of elements. In order to get the distinct combinations, you can convert each combination to a set and store it in a set() object to remove duplicates. Here's an example:

main.py
import itertools

def get_distinct_combinations(s):
    distinct_combinations = set()
    for i in range(1, len(s) + 1):
        for combination in itertools.combinations(s, i):
            distinct_combinations.add(frozenset(combination))
    return distinct_combinations

# Example usage
my_set = {1, 2, 3}
result = get_distinct_combinations(my_set)
print(result)
366 chars
14 lines

In the example above, we start by importing the itertools module. We define a function called get_distinct_combinations() that takes a set as an argument. We initialize an empty set() called distinct_combinations to keep track of the distinct combinations.

We then loop through all possible combination lengths, from 1 to the length of the set. For each combination length i, we generate all possible combinations using the itertools.combinations() function. We convert each combination to a frozenset object (which is immutable and can be added to a set() object) and add it to the distinct_combinations set. By using frozenset, we ensure that the order of the elements in each combination is not considered for the purpose of de-duplication.

Once we have generated all the distinct combinations, we return the distinct_combinations set. In this example with {1, 2, 3}, the output will be:

main.py
{frozenset({1}), frozenset({2}), frozenset({1, 2}), frozenset({3}), frozenset({1, 3}), frozenset({2, 3}), frozenset({1, 2, 3})}
128 chars
2 lines

gistlibby LogSnag