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

相关文章

Cpy和Python的效率对比

Python 语言的初学者, 特别是"惊奇者"(也就是那种第一眼就被毫无意义的某些特性吸引, 之后持续说服自己的人)认为 Python 不需要 C 语言的 for 语句, 因为他们能用优...

pyqt5简介及安装方法介绍

pyqt5简介及安装方法介绍

本文研究的主要是pyqt5简介及安装方法介绍的有关内容,具体如下。 pyqt5介绍 pyqt5是一套Python绑定Digia QT5应用的框架。它可用于Python 2和3。本教程使用...

Python 十六进制整数与ASCii编码字符串相互转换方法

在使用Pyserial与STM32进行通讯时,遇到了需要将十六进制整数以Ascii码编码的字符串进行发送并且将接收到的Ascii码编码的字符串转换成十六进制整型的问题。查阅网上的资料后,...

django开发之settings.py中变量的全局引用详解

django开发之settings.py中变量的全局引用详解

本文主要介绍的是django中settings.py中变量的全局引用的相关资料,下面话不多说,来看看详细的介绍吧。 前言 在settings.py中添加自定义变量,可以通过setting...

Python绘制正余弦函数图像的方法

Python绘制正余弦函数图像的方法

今天打算通过绘制正弦和余弦函数,从默认的设置开始,一步一步地调整改进,让它变得好看,变成我们初高中学习过的图象那样。通过这个过程来学习如何进行对图表的一些元素的进行调整。 01. 简单绘...