pythonsubsetpowerset

Find subsets of a set in python (order does not matter)


I need to find the subsets of a set L = [0, 3, 4, 6, 9, 11, 12, 13]. I saw online the following solution:

def powerset(s):
    x = len(s)
    masks = [1 << i for i in range(x)]
    for i in range(1 << x):
        yield [ss for mask, ss in zip(masks, s) if i & mask]

print(list(powerset(L)))

However, this code will also return my full set L and an empty set which I do not want.

I was looking for a way to do this directly in python without using any additional packages.


Solution

  • Here is a pretty simple solution. I did it as a list of sets, but you could easily swap to a list of tuples if you'd rather.

    def subsets(r):
        res = []
        for i in range(1, 2**len(r)-1):
            key = format(i, '#010b')
            res.append({x for j, x in enumerate(r) if key[~j] == '1'})
        return res
    
    L = [0, 3, 4, 6, 9, 11, 12, 13]
    print(subsets(L))
    

    Edit: I just realised I pretty much just replicated the solution you already had, and probably in a less efficient way. Oh well I will leave this up as it does answer the question.