2014-05-08 52 views
1

设设置A=set([1,2,3]) and set B=set()现在,我需要反复生成所有可能的组合像 set([1]) set([2]) set([3]) set([1,2]) set([1,3]) set([2,3]) set([1,2,3]) 我知道公然我可以使用itertools的powergenerator配方,但伪代码在下面的表格进一步条件检查(子集条件和密度条件)我怎么能反复生成元素,以所有可能的组合成套

a=set() 
b=set([1,2,3]) 
for i in b-a: 
    a=a|set([i])  
    for j in a: 
     print a-set([j]) 

     if den(a-set[j])>=0.6:#check density criteria 
       # check if a-set([j]) is subset of a on ordering criteria  

的上面即打印语句,打印集([J])已给定的输出,如下

set([]) 
set([2]) 
set([1]) 
set([2, 3]) 
set([1, 3]) 
set([1, 2]) 

但我需要有输出以下格式

set([1]) 
set([2]) 
set([3]) 
set([2, 3]) 
set([1, 3]) 
set([1, 2]) 
set([1,2,3]) 
+0

为什么不使用itertools的powerset配方并过滤掉你不想要的结果? – user2357112

+0

@ user2014111你检查了下面的答案吗? –

回答

1

您可以使用itertools.combinations

from itertools import combinations 

list(combinations(b, 1)) + list(combinations(b, 2)) + list(combinations(b, 3)) 
#[(1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)] 
0

尝试使用iterto0ls找到子集。 itertools

import itertools 
a=[1,2,3] 
subsets=[] 
for i in range(1,4): 
    for j in itertools.combinations(a,i): 
     subsets.append(list(j)) 
print subsets 

#output=[[1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]] 

if set is method。你可以链接它们,

map(set,subsets) 
+0

@ user2014111 j已转换为列表..请参阅更新 –

相关问题