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

前端 未结 28 2776
庸人自扰
庸人自扰 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:40

    Just a quick power set refresher !

    Power set of a set X, is simply the set of all subsets of X including the empty set

    Example set X = (a,b,c)

    Power Set = { { a , b , c } , { a , b } , { a , c } , { b , c } , { a } , { b } , { c } , { } }

    Here is another way of finding power set:

    def power_set(input):
        # returns a list of all subsets of the list a
        if (len(input) == 0):
            return [[]]
        else:
            main_subset = [ ]
            for small_subset in power_set(input[1:]):
                main_subset += [small_subset]
                main_subset += [[input[0]] + small_subset]
            return main_subset
    
    print(power_set([0,1,2,3]))
    

    full credit to source

提交回复
热议问题