2 回答

TA貢獻1797條經驗 獲得超6個贊
與這篇文章類似,您要查找的內容稱為圖的連接組件。一個簡單的方法是用 構建一個圖networkx,然后找到connected_components:
tuplist = [('a','b'),('a','c'),('e','f'),('f','c'),('d','z'),('z','x')]
import networkx as nx
G=nx.Graph()
G.add_edges_from(tuplist)
list(nx.connected_components(G))
# [{'a', 'b', 'c', 'e', 'f'}, {'d', 'x', 'z'}]

TA貢獻1802條經驗 獲得超5個贊
可選的遞歸解決方案,雖然不像@yatu的解決方案那樣優雅networkx:
tuplist = [('a','b'),('a','c'),('e','f'),('f','c'),('d','z'),('z','x')]
def get_graphs(start, c = [], seen = []):
_r = [b for a, b in tuplist if a == start and b not in seen]+[a for a, b in tuplist if b == start and a not in seen]
if _r:
yield from [i for b in _r for i in get_graphs(b, c=c+[start, b, *_r], seen = seen+[start, b])]
else:
yield set(c)
_r = [a for a, _ in tuplist if a not in seen]
yield from ([] if not _r else get_graphs(_r[0], c = [], seen= seen))
result = list(get_graphs(tuplist[0][0]))
final_result = [a for i, a in enumerate(result) if all(all(k not in b for k in a) for b in result[i+1:])]
to_tuples = list(map(tuple, final_result))
輸出:
[('f', 'e', 'a', 'c', 'b'), ('z', 'd', 'x')]
添加回答
舉報