📌  相关文章
📜  Python程序获取给定大小的集合的所有子集

📅  最后修改于: 2021-04-22 09:32:56             🧑  作者: Mango

给定一个集合,编写一个Python程序以生成列表中给定集合大小n的所有可能子集。

例子:

Input : {1, 2, 3}, n = 2
Output : [{1, 2}, {1, 3}, {2, 3}]

Input : {1, 2, 3, 4}, n = 3
Output : [{1, 2, 3}, {1, 2, 4}, {1, 3, 4}, {2, 3, 4}]

我们已经在本文中使用朴素方法讨论了相同的问题。本文重点介绍使用Python方法打印集合中给定大小的所有子集的方法。

Python具有itertools.combinations(iterable, n) ,它从可迭代输入中返回元素的n个长度的子序列。这可用于打印一组给定大小的所有子集。现在,我们有各种替代方法可以使用此函数。

代码1:
只需在itertools.combinations()中将集合作为可迭代对象并将大小作为参数传递,即可直接获取组合列表。

# Python Program to Print 
# all subsets of given size of a set
  
import itertools
  
def findsubsets(s, n):
    return list(itertools.combinations(s, n))
  
# Driver Code
s = {1, 2, 3}
n = 2
  
print(findsubsets(s, n))
输出:
[(1, 2), (1, 3), (2, 3)]

代码2:
我们还可以使用上述方法的替代方法,该方法是集合映射itertools.combinations()函数。

# Python Program to Print 
# all subsets of given size of a set
  
import itertools
from itertools import combinations, chain
  
def findsubsets(s, n):
    return list(map(set, itertools.combinations(s, n)))
      
# Driver Code
s = {1, 2, 3}
n = 2
  
print(findsubsets(s, n))
输出:
[{1, 2}, {1, 3}, {2, 3}]

代码3:
另一种方法是在itertools.combinations()函数使用for循环,并将组合集附加到列表中。

# Python Program to Print 
# all subsets of given size of a set
  
import itertools
# def findsubsets(s, n):
def findsubsets(s, n):
    return [set(i) for i in itertools.combinations(s, n)]
      
# Driver Code
s = {1, 2, 3, 4}
n = 3
  
print(findsubsets(s, n))
输出:
[{1, 2, 3}, {1, 2, 4}, {1, 3, 4}, {2, 3, 4}]