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中输入一个以空格为间隔的数组方法

很多时候要从键盘连续输入一个数组,并用空格隔开,Python中的实现方法如下: >>> str_in = input('请以空格为间隔连续输入一个数组:') 然后...

Django中使用CORS实现跨域请求过程解析

跨域请求: 请求url包含协议、网址、端口,任何一种不同都是跨域请求。 1.安装cors模块 pip install django-cors-headers 2.添加应用 IN...

Python动态语言与鸭子类型详解

今天来说说编程语言中的动态类型语言与鸭子类型。 动态语言 维基百科对动态语言的定义: 动态编程语言是一类在运行时可以改变其结构的语言:例如新的函数、对象、甚至代码可以被引进,已有的函数...

Python translator使用实例

1.string.maketrans设置字符串转换规则表(translation table) allchars = string.maketrans('...

Python获取CPU、内存使用率以及网络使用状态代码

由于psutil已更新到3.0.1版本,最新的代码如下: #!/usr/bin/env python import os import time import sys import...