0
点赞
收藏
分享

微信扫一扫

求一个集合的所有子集 Python实现

炽凤亮尧 2023-01-13 阅读 78


​​求一个集合的所有子集 Python实现​​



#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 23 16:59:07 2018

@author: luogan
"""

def PowerSetsBinary(items):
#generate all combination of N items
N = len(items)
#enumerate the 2**N possible combinations
set_all=[]
for i in range(2**N):

#print('i=',i)

#print('__'*10)
combo = []
for j in range(N):
#print('j=',j)


#test jth bit of integer i
if(i >> j ) % 2 == 1:

print('i=',i,'j=',j)



combo.append(items[j])

#print(combo)
#yield combo
#print(combo)
set_all.append(combo)
return set_all

a=list(range(3))


out= PowerSetsBinary(a)

print(out

[[], [0], [1], [0, 1], [2], [0, 2], [1, 2], [0, 1, 2]]









举报

相关推荐

0 条评论