簡體   English   中英

使用Python查找元組中的所有常見元素和組合

[英]Find all common elements and combinations in tuples using Python

我試圖將所有在元組中共享公共元素的值歸為一組-本質上是找到任意組合的數字組(不需要順序)-我有元組。 例如,如果我有以下一組元組:

(1,2),(1,3),(1,5),(1,6),(2,3),(2,5),(2,7),(3,5),(3,7),(3,9)

我想了解所有共同點。 對於此示例,這將是:

1, 2, 3, 5  (since I have any combination of 1,2,3 and 5)
2, 3, 7 (since I have any combination of 2,3 and 7)
1, 6 (since I have any combination of 1 and 6)
3, 9 (since I have any combination of 3 and 9)

關於如何解決這個問題有什么想法嗎?

如@alfasin所述,您正在尋找圖形中的最大集團

無向圖中G =(V,E)的集團C是頂點C⊆V的子集,因此每兩個不同的頂點相鄰。

最大派系是無法通過包含一個或多個相鄰頂點來擴展的派系,即,一個派系並不存在於較大派系的頂點集中。

帶有find_cliques NetworkX是您的朋友:

>>> import networkx as nx
>>> G = nx.Graph([(1,2),(1,3),(1,5),(1,6),(2,3),(2,5),(2,7),(3,5),(3,7),(3,9)])
>>> list(nx.find_cliques(G))
[[3, 9], [3, 2, 1, 5], [3, 2, 7], [6, 1]]

如果要將圖定義為小集團的結合並查看它們是否合並為大集團,則可以使用itertools.combinations遍歷輸入集團的所有邊緣,並將它們添加到圖中:

import networkx as nx
from itertools import combinations

G = nx.Graph()

cliques = [(1,2,3),(1,2,4),(1,3,4),(2,3,4)]

for clique in cliques:
  for vertices in combinations(clique, r=2):
    G.add_edge(*vertices)

print(list(nx.find_cliques(G)))
# [[1, 2, 3, 4]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM