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

相关文章

通过cmd进入python的实例操作

通过cmd进入python的实例操作

通过cmd启动Python需要先设置系统环境,设置步骤如下: 1、首先,在桌面找到 “计算机” 右键 找到 “属性”或者按下 win 键 再右键“计算机” 找到 “属性”也可以。如下图所...

pytorch使用 to 进行类型转换方式

pytorch使用 to 进行类型转换方式

在程序中,有多种方法进行强制类型转换。 本博文将介绍一个非常常用的方法:to()方法。 我们通常使用它来进行GPU和CPU的类型转换,但其实也可以用来进行torch的dtype转换。 常...

python 实现二维列表转置

python 二维列表转置 def transpose(self, matrix): new_matrix = [] for i in range(len(matri...

详解pandas安装若干异常及解决方案总结

详解pandas安装若干异常及解决方案总结

在为Python安装第三方工具pandas出现了若干问题。 当我在cmd命令环境输入pip install pandas准备安装pandas时,出现了错误提示:Microsoft Vis...

详解Python文本操作相关模块

详解Python文本操作相关模块 linecache——通过使用缓存在内部尝试优化以达到高效从任何文件中读出任何行。 主要方法: linecache.getline(file...