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

前端 未结 28 2795
庸人自扰
庸人自扰 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条回答
  •  Happy的楠姐
    2020-11-22 05:59

    This is wild because none of these answers actually provide the return of an actual Python set. Here is a messy implementation that will give a powerset that actually is a Python set.

    test_set = set(['yo', 'whatup', 'money'])
    def powerset( base_set ):
        """ modified from pydoc's itertools recipe shown above"""
        from itertools import chain, combinations
        base_list = list( base_set )
        combo_list = [ combinations(base_list, r) for r in range(len(base_set)+1) ]
    
        powerset = set([])
        for ll in combo_list:
            list_of_frozensets = list( map( frozenset, map( list, ll ) ) ) 
            set_of_frozensets = set( list_of_frozensets )
            powerset = powerset.union( set_of_frozensets )
    
        return powerset
    
    print powerset( test_set )
    # >>> set([ frozenset(['money','whatup']), frozenset(['money','whatup','yo']), 
    #        frozenset(['whatup']), frozenset(['whatup','yo']), frozenset(['yo']),
    #        frozenset(['money','yo']), frozenset(['money']), frozenset([]) ])
    

    I'd love to see a better implementation, though.

提交回复
热议问题