how to get all proper subsets of a set in python

Here's a recursive approach to getting all proper subsets of a set in Python:

main.py
def get_subsets(s):
    """Returns a list of all subsets of set s"""
    if not s:
        return [[]]
    x = s.pop()
    subsets = get_subsets(s)
    new_subsets = []
    for subset in subsets:
        new_subsets.append(subset + [x])
    return subsets + new_subsets

def get_proper_subsets(s):
    """Returns a list of all proper subsets of set s"""
    subsets = get_subsets(s)
    return [subset for subset in subsets if subset != s]
440 chars
16 lines

The get_subsets function is a helper function that returns all possible subsets of a given set s. The get_proper_subsets function uses get_subsets to get all possible subsets, and then filters out the set s itself (which is not a proper subset).

We can use the code like this:

main.py
>>> s = set([1, 2, 3])
>>> get_proper_subsets(s)
[[1], [2], [3], [1, 2], [1, 3], [2, 3]]
89 chars
4 lines

gistlibby LogSnag