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

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

    Perhaps the question is getting old, but I hope my code will help someone.

    def powSet(set):
        if len(set) == 0:
           return [[]]
        return addtoAll(set[0],powSet(set[1:])) + powSet(set[1:])
    
    def addtoAll(e, set):
       for c in set:
           c.append(e)
       return set
    

提交回复
热议问题