获得了一组在Python的子集 [英] Getting the subsets of a set in Python

查看:207
本文介绍了获得了一组在Python的子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们需要编写一个函数,提供了一组所有子集的列表。功能和文档测试如下。我们需要完成的功能的全高清

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 definition of the function

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)    


它不使用任何内置的功能


It has to not use any built-in function

我的方法是增加元素到休息和恢复他们,但我并不真正熟悉如何使用设置,列表中的Python。

My approach is to add "element" into rest and return them all, but I am not really familiar how to use set, list in Python.

推荐答案

幂()配方中 itertools文档

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的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆