Getting the subsets of a set in Python

前端 未结 7 2089
清歌不尽
清歌不尽 2020-12-03 23:19

Suppose we need to write a function that gives the list of all the subsets of a set. The function and the doctest is given below. And we need to complete the whole definitio

7条回答
  •  星月不相逢
    2020-12-03 23:31

    The usual implementation of powerset on list goes something like this:

    def powerset(elements):
        if len(elements) > 0:
            head = elements[0]
            for tail in powerset(elements[1:]):
                yield [head] + tail
                yield tail
        else:
            yield []
    

    Just needs a little bit of adaptation to deal with set.

提交回复
热议问题