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

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

    Here is my quick implementation utilizing combinations but using only built-ins.

    def powerSet(array):
        length = str(len(array))
        formatter = '{:0' + length + 'b}'
        combinations = []
        for i in xrange(2**int(length)):
            combinations.append(formatter.format(i))
        sets = set()
        currentSet = []
        for combo in combinations:
            for i,val in enumerate(combo):
                if val=='1':
                    currentSet.append(array[i])
            sets.add(tuple(sorted(currentSet)))
            currentSet = []
        return sets
    

提交回复
热议问题