求一个集合的所有子集 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]]

猜你喜欢

转载自blog.csdn.net/luoganttcc/article/details/80785149