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

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

    If you're looking for a quick answer, I just searched "python power set" on google and came up with this: Python Power Set Generator

    Here's a copy-paste from the code in that page:

    def powerset(seq):
        """
        Returns all the subsets of this set. This is a generator.
        """
        if len(seq) <= 1:
            yield seq
            yield []
        else:
            for item in powerset(seq[1:]):
                yield [seq[0]]+item
                yield item
    

    This can be used like this:

     l = [1, 2, 3, 4]
     r = [x for x in powerset(l)]
    

    Now r is a list of all the elements you wanted, and can be sorted and printed:

    r.sort()
    print r
    [[], [1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 4], [1, 3], [1, 3, 4], [1, 4], [2], [2, 3], [2, 3, 4], [2, 4], [3], [3, 4], [4]]
    

提交回复
热议问题