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.py199 chars11 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