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.py366 chars14 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.py128 chars2 lines
gistlibby LogSnag