Python实现求一个集合所有子集的示例
作者:tszw1007 时间:2022-09-01 20:56:51
方法一:回归实现
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
来源:https://blog.csdn.net/tszw1007/article/details/77871133
标签:python,集合,子集
0
投稿
猜你喜欢
Python实现批量翻译的示例代码
2023-02-27 04:24:12
牢不可破的九宫格布局
2009-07-24 12:40:00
QQ聊天窗口链接提示效果代码
2008-12-16 12:59:00
一文教会你用python连接并简单操作SQLserver数据库
2024-01-17 14:11:34
Django项目连接MongoDB的三种方法
2022-05-27 05:23:43
Windows下MySQL8.0.11社区绿色版安装步骤图解
2024-01-14 23:02:34
TypeScript入门-基本数据类型
2024-06-07 15:56:50
python实现水仙花数实例讲解
2021-04-05 11:38:05
Django框架之中间件MiddleWare的实现
2021-03-25 15:08:30
Python爬虫 scrapy框架爬取某招聘网存入mongodb解析
2023-06-23 09:35:59
Python实现线性插值和三次样条插值的示例代码
2023-12-04 19:19:42
TensorFlow使用Graph的基本操作的实现
2023-04-10 22:22:37
Python根据输入参数计算结果的实例方法
2021-12-15 08:30:45
巧妙使用python opencv库玩转视频帧率
2023-02-01 13:54:30
做了CDN加速的ASP网站获取用户真实IP程序
2011-02-16 10:59:00
用python开发一款操作MySQL的小工具
2024-01-26 08:55:19
c#编写的高并发数据库控制访问代码
2024-01-16 04:57:04
微信小程序分享海报生成的实现方法
2024-05-02 17:29:49
eWebEditor不支持IE8的解决方法
2009-11-02 10:59:00
由黄钻等级图标处理引发的思考
2009-11-16 12:37:00