How to get all subsets of a set? (powerset)

前端 未结 28 2513
庸人自扰
庸人自扰 2020-11-22 05:18

Given a set

{0, 1, 2, 3}

How can I produce the subsets:

[set(),
 {0},
 {1},
 {2},
 {3},
 {0, 1},
 {0, 2},
 {0, 3},
 {1, 2}         


        
28条回答
  •  一生所求
    2020-11-22 05:52

    I just wanted to provide the most comprehensible solution, the anti code-golf version.

    from itertools import combinations
    
    l = ["x", "y", "z", ]
    
    def powerset(items):
        combo = []
        for r in range(len(items) + 1):
            #use a list to coerce a actual list from the combinations generator
            combo.append(list(combinations(items,r)))
        return combo
    
    l_powerset = powerset(l)
    
    for i, item in enumerate(l_powerset):
        print "All sets of length ", i
        print item
    

    The results

    All sets of length 0

    [()]

    All sets of length 1

    [('x',), ('y',), ('z',)]

    All sets of length 2

    [('x', 'y'), ('x', 'z'), ('y', 'z')]

    All sets of length 3

    [('x', 'y', 'z')]

    For more see the itertools docs, also the wikipedia entry on power sets

提交回复
热议问题