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')]
添加回答
举报