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

相关文章

使用TensorFlow-Slim进行图像分类的实现

参考 https://github.com/tensorflow/models/tree/master/slim 使用TensorFlow-Slim进行图像分类 准备 安装Tensor...

Python的包管理器pip更换软件源的方法详解

pip镜像源 在国内如果不使用 VPN 是没办法好好使用 pip 命令安装任何 Python 包的。所以另一个选择就是使用国内各大厂的开源镜像源。 目前国内靠谱的 pip 镜像源有:...

python学生管理系统学习笔记

本文实例为大家分享了python学生管理系统的具体代码,供大家参考,具体内容如下 基于列表存储的学生管理系统,实现如下功能 ================== 学生管理系统 1、添加...

python基础教程之基本内置数据类型介绍

Python基本内置数据类型有哪些 一些基本数据类型,比如:整型(数字)、字符串、元组、列表、字典和布尔类型。随着学习进度的加深,大家还会接触到更多更有趣的数据类型,python初学者入...

Django中的FBV和CBV用法详解

Django中的FBV和CBV用法详解

FBV FBV,即 func base views,函数视图,在视图里使用函数处理请求。 以用户注册代码为例, 使用两个函数完成注册 初级注册代码 def register(req...