求一个集合的所有子集 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]]
posted @ 2018-06-23 17:12  luoganttcc  阅读(342)  评论(0编辑  收藏  举报