2014-05-08 51 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已轉換爲列表..請參閱更新 –

相關問題