在Python中获取集合的子集

ger*_*een 6 python algorithm math combinatorics

假设我们需要编写一个函数来给出集合中所有子集的列表.函数和doctest如下.我们需要完成函数的整个定义

def subsets(s):
   """Return a list of the subsets of s.

   >>> subsets({True, False})
   [{False, True}, {False}, {True}, set()]
   >>> counts = {x for x in range(10)} # A set comprehension
   >>> subs = subsets(counts)
   >>> len(subs)
   1024
   >>> counts in subs
   True
   >>> len(counts)
   10
   """
   assert type(s) == set, str(s) + ' is not a set.'
   if not s:
       return [set()]
   element = s.pop() 
   rest = subsets(s)
   s.add(element)    
Run Code Online (Sandbox Code Playgroud)

它必须不使用任何内置函数

我的方法是将"元素"添加到休息中并将它们全部返回,但我并不熟悉如何在Python中使用set,list.

Ray*_*ger 15

查看itertools文档中的powerset()配方.

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))
Run Code Online (Sandbox Code Playgroud)