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 IDLE 背景以及字体大小的修改方法

python IDLE 背景以及字体大小的修改方法

为了保护眼睛,决定把白色背景换掉: 1 首先,在已经下载好的python文件目录下,找到config-highlight.def文件,我的是在H:\python\python3**\...

python文件写入实例分析

本文实例讲述了python文件写入的用法。分享给大家供大家参考。具体分析如下: Python中wirte()方法把字符串写入文件,writelines()方法可以把列表中存储的内容写入文...

理想高通滤波实现Python opencv示例

理想高通滤波实现Python opencv示例

理想高通滤波实现 python opencv import numpy as np import cv2 from matplotlib import pyplot as plt...

python编写弹球游戏的实现代码

 弹球游戏: from tkinter import * import time import random tk=Tk() #创建一个界面 tk...

Python小进度条显示代码

有的时候程序需要有进度条显示,比如说安装程序、下载文件等场合。 下面有一段小程序可达到效果 程序代码 import time for i in range(0, 101, 2):...