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

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

    A variation of the question, is an exercise I see on the book "Discovering Computer Science: Interdisciplinary Problems, Principles, and Python Programming. 2015 edition". In that exercise 10.2.11, the input is just an integer number, and the output should be the power sets. Here is my recursive solution (not using anything else but basic python3 )

    def powerSetR(n):
        assert n >= 0
        if n == 0:
            return [[]]
        else:
            input_set = list(range(1, n+1)) # [1,2,...n]
            main_subset = [ ]
            for small_subset in powerSetR(n-1):
                main_subset += [small_subset]
                main_subset += [ [input_set[-1]] + small_subset]
            return main_subset
    
    superset = powerSetR(4)
    print(superset)       
    print("Number of sublists:", len(superset))
    

    And the output is

    [[], [4], [3], [4, 3], [2], [4, 2], [3, 2], [4, 3, 2], [1], [4, 1], [3, 1], [4, 3, 1], [2, 1], [4, 2, 1], [3, 2, 1], [4, 3, 2, 1]] Number of sublists: 16

提交回复
热议问题