2017-04-21 59 views
0

我嘗試遍歷兩個集合列表,其中一個列表只包含一個集合,並將該集合附加到具有最大交集的列表直到所有集合都被追加。對於每個集合order_of_sets中的新元素應該重複該過程。該算法應該像貪婪算法一樣運作。如何添加具有最多交集元素的列表

 s1=set([1,2,3,4,5,6,7,8,9,10]) 
     s2=set([1,3,56,8,9]) 
     s3=set([1,4,5,6,7,8,10,22,23,24,25]) 
     s4=set([7,8,9,10,23,14,22,23,24,30,56]) 
     list_of_sets=[s2,s3,s4] 
     order_of_sets=[s1] 

     for x in list_of_set: 
      for y in order_of_sets: 
      if len(x.intersection(y))==max[len(x.intersection(y))]: 
       order_of_lists.append(y) 
       list_of_sets.remove(y) 

我想要的到底是什麼:

order_of_sets=[s1,s3,s4,s2]  

也許我可以定義評估路口的長度的函數,但我不知道怎麼辦。

+0

你的預期輸出是什麼?你能否在你的描述中寫下這個。 – qbzenker

+0

「有最大的交集」與其他設置? – user2357112

+0

按集合順序設置的集合將是s1。我想從list_of_sets中添加與s1具有最大交集的集合。這將是s3。之後,我希望下一個完成第3集。最大的交叉點將介於s3和s4之間。 –

回答

0
s1 = {1,2,3,4,5,6,7,8,9,10} # in python 3 this set notation is easier on the eyes 
s2 = {1,3,56,8,9} 
s3 = {1,4,5,6,7,8,10,22,23,24,25} 
s4 = {7,8,9,10,23,14,22,23,24,30,56} 

list_of_sets = [s2,s3,s4] 
order_of_sets = [s1] 

while list_of_sets: 
    best_set = max(list_of_sets, key=lambda s: len(s.intersection(order_of_sets[-1]))) # gets the set from list_of_sets having the largest intersection with the last set from order_of_sets 
    list_of_sets.remove(best_set) 
    order_of_sets.append(best_set) 


print(order_of_sets) 

[{1,2,3,4,5,6,7,8,9,10},{1,4,5,6,7,8,10 ,22,23,24,25},{7,8,9,10,14,22,23,24,56,30},{1,3, ,8,9,56}]

+0

非常感謝我會嘗試它!我知道這會很簡單,我的知識不足。第二行中「[-1]」的含義是什麼? –

+0

它從'order_of_sets'獲得最後一項# – Guillaume

+0

啊當然,因爲第一個索引爲0 –

相關問題