how to get all subsets of a set in python

Here's a function in Python that returns all possible subsets of a given set using recursion and itertools:

main.py
import itertools
    
def get_subsets(s):
    # Use recursion to generate all possible subsets
    if len(s) == 0:
        return [[]]
    
    subsets = []
    first_elt = s[0]
    rest_list = s[1:]
    for prev_subset in get_subsets(rest_list):
        subsets.append(prev_subset)
        new_subset = prev_subset[:] + [first_elt]
        subsets.append(new_subset)
    
    # Remove duplicate subsets using set and return sorted list
    return sorted(list(set(subsets)))

# Example usage
set_input = set([1, 2, 3])
subsets = get_subsets(list(set_input))
print(subsets)
573 chars
23 lines

This code uses recursion to generate all possible subsets of a given set. It first checks if the set is empty and returns an empty subset in that case. Otherwise, it takes the first element of the set and generates all subsets of the remaining elements recursively using the get_subsets function. It then appends these previous subsets to the current list of subsets, and appends a new subset consisting of the first element and a previous subset. To remove duplicates, the function first converts the subsets to a set (which removes duplicates), and then converts the set back to a sorted list. Finally, an example usage is shown by generating all subsets of the set {1, 2, 3}.

gistlibby LogSnag