Getting the subsets of a set in Python

前端 未结 7 2084
清歌不尽
清歌不尽 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:56

    Look at the powerset() recipe in the itertools docs.

    from itertools import chain, combinations
    
    def powerset(iterable):
        "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
        s = list(iterable)
        return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
    
    def subsets(s):
        return map(set, powerset(s))
    

提交回复
热议问题