Python实现求一个集合所有子集的示例

yipeiwu_com5年前Python基础

方法一:回归实现

def PowerSetsRecursive(items):
  """Use recursive call to return all subsets of items, include empty set"""
  
  if len(items) == 0:
    #if the lsit is empty, return the empty list
    return [[]]
  
  subsets = []
  first_elt = items[0] #first element
  rest_list = items[1:]
  
  #Strategy:Get all subsets of rest_list; for each of those subsets, a full subset list
  #will contain both the original subset as well as a version of the sebset that contains the first_elt
  
  for partial_sebset in PowerSetsRecursive(rest_list):
    subsets.append(partial_sebset)
    next_subset = partial_sebset[:] +[first_elt]
    subsets.append(next_subset)
  return subsets

def PowerSetsRecursive2(items):
  # the power set of the empty set has one element, the empty set
  result = [[]]
  for x in items:
    result.extend([subset + [x] for subset in result])
  return result 

方法二:二进制法

def PowerSetsBinary(items): 
  #generate all combination of N items 
  N = len(items) 
  #enumerate the 2**N possible combinations 
  for i in range(2**N): 
    combo = [] 
    for j in range(N): 
      #test jth bit of integer i 
      if(i >> j ) % 2 == 1: 
        combo.append(items[j]) 
    yield combo 

以上这篇Python实现求一个集合所有子集的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

详谈Numpy中数组重塑、合并与拆分方法

1.数组重塑 1.1一维数组转变成二维数组 通过reshape( )函数即可实现,假设data是numpy.array类型的一维数组array([0, 1, 2, 3, 4, 5, 6,...

Django框架ORM数据库操作实例详解

Django框架ORM数据库操作实例详解

本文实例讲述了Django框架ORM数据库操作。分享给大家供大家参考,具体如下: 测试数据:BookInfo表 PeopleInfo表 一.增加 1.save: 对象 = 模型类...

pytorch实现mnist分类的示例讲解

torchvision包 包含了目前流行的数据集,模型结构和常用的图片转换工具。 torchvision.datasets中包含了以下数据集 MNIST COCO(用于图像标注和目标检测...

Python用5行代码写一个自定义简单二维码

Python用5行代码写一个自定义简单二维码

python的优越之处就在于他可以直接调用已经封装好的包 首先,下载pillow和qrcode包  终端下键入一下命令: pip3 install pillow #pyt...

Python对列表的操作知识点详解

Python对列表的操作知识点详解

Python的数据结构有列表、元组、集合、字典等,可以吧列表当成一个清单,是有序的,我们可以通过索引访问到列表中的元素,列表还可以进行修改、新增和删除的操作。列表中的数据类型是不限制的,...