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

相关文章

Python判断一个文件夹内哪些文件是图片的实例

如下所示: def is_img(ext): ext = ext.lower() if ext == '.jpg': return True elif ext == '.p...

python对列进行平移变换的方法(shift)

在进行数据操作时, 经常会碰到基于同一列进行错位相加减的操作, 即对某一列进行向上或向下平移(shift). 往常, 我们都会使用循环进行操作, 但经过查阅相关资料, 发现结合panda...

win10下tensorflow和matplotlib安装教程

win10下tensorflow和matplotlib安装教程

本文介绍了一系列安装教程,具体如下 1.安装Python 版本选择是3.5.1,因为网上有些深度学习实例用的就是这个版本,跟他们一样的话可以避免版本带来的语句规范问题 python的下载...

机器学习的框架偏向于Python的13个原因

机器学习的框架偏向于Python的13个原因

13个机器学习的框架偏向于Python的原因,供大家参考,具体内容如下 前言 主要有以下原因: 1. Python是解释语言,程序写起来非常方便 写程序方便对做机器学习的人很重要。...

python图片验证码生成代码

本文实例为大家分享了python图片验证码实现代码,供大家参考,具体内容如下 #!/usr/bin/env python # -*- coding: UTF-8 -*- impo...