python - 在 Python 中获取集合的子集

标签 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)    

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

我的方法是在rest中添加“element”,然后全部返回,但是我不太熟悉如何在Python中使用set、list。

最佳答案

查看powerset() 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))

关于python - 在 Python 中获取集合的子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7988695/

相关文章:

algorithm - 给出组合时如何计算索引(字典顺序)

go - 试图在 go 中计算 pi,我做错了什么? math.Cos 可能有问题?

python - Jupyter/IPython Notebook 文本编辑为 markdown

python - 十进制转二进制的python算法

python - 在 Numpy 1.6.1 中将 float32 数组转换为 datetime64

python - 在 Python : Create a dictionary from a list of keys, 中但将所有值设置为 0?

algorithm - 平均分配点数

algorithm - 这种贪婪调度算法在哪里变得次优?

python - 这段代码执行后栈会不会为空?

php - 寻找一个钟形曲线公式来呈现在一个范围内具有零到完全影响的数据