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

yipeiwu_com6年前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设计】。

相关文章

python模拟enum枚举类型的方法小结

本文实例总结了python模拟enum枚举类型的方法。分享给大家供大家参考。具体分析如下: python中没有enum枚举类型,可能python认为这玩意压根就没用,下面列举了三种方法模...

浅谈Python中的私有变量

私有变量表示方法 在变量前加上两个下划线的是私有变量。 class Teacher(): def __init__(self,name,level): self.__na...

pyside写ui界面入门示例

PySide是一个免费的软件,与PyQt不同之处在于使用了LGPL,允许PySide免费的开发商业软件。 PySide有15个模块。这些模块支持对GUI,多媒体,XML,网络以及数据库进...

浅析python,PyCharm,Anaconda三者之间的关系

一、它们是什么? 1.python Python是一种跨平台的计算机程序设计语言,简单来说,python就是类似于C,Java,C++等,一种编程语言。 2.Anaconda Anaco...

浅谈Matplotlib简介和pyplot的简单使用——文本标注和箭头

浅谈Matplotlib简介和pyplot的简单使用——文本标注和箭头

 在使用pyplot画图的时候,有时会需要在图上标注一些文字,如果曲线靠的比较近,最好还能用箭头指出标注文字和曲线的对应关系。这里就介绍文字标注和箭头的使用。 添加标注使用py...