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

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

    import math    
    def printPowerSet(set,set_size): 
        pow_set_size =int(math.pow(2, set_size))
        for counter in range(pow_set_size):
        for j in range(set_size):  
            if((counter & (1 << j)) > 0):
                print(set[j], end = "")
        print("")
    set = ['a', 'b', 'c']
    printPowerSet(set,3)
    

提交回复
热议问题