简体   繁体   English

基于公共值合并表示图边的元组列表

[英]Merge list of tuples representing graph edges based off common values

I am attempting to write some python code that if given a list of tuples representing directed edges on a graph, I return all the possible paths.我正在尝试编写一些 python 代码,如果给定一个表示图形上有向边的元组列表,我将返回所有可能的路径。 The graph, in this case, will not contain a cycle and each one of the nodes of the graph can only connect to one other node.在这种情况下,图将不包含循环,并且图中的每个节点只能连接到另一个节点。 The input would be in the form输入将采用以下形式

[(1909, 1910), (1910, 1900), (1922, 1920), (1935,1922), (1940, 1939)]

and should return something in the form of并且应该以以下形式返回一些东西

[(1909,1910,1900), (1935,1922,1920), (1940,1939)]

I'm not sure how to go about this cause the order must be maintained, ie because 1922 comes before 1920 and 1935 comes before 1922, the resulting answer must be (1935,1922,1920)我不知道如何解决这个问题,因为必须保持顺序,即因为 1922 年在 1920 年之前,1935 年在 1922 年之前,结果答案必须是 (1935,1922,1920)

Any ideas on how to achieve this?关于如何实现这一目标的任何想法?

You can convert the tuples to a dictionary keyed on the first item and then progressively merge the items by linking the last element of each item.您可以将元组转换为以第一个项目为键的字典,然后通过链接每个项目的最后一个元素来逐步合并项目。

tuples = [(1909, 1910), (1910, 1900), (1922, 1920), (1935,1922), (1940, 1939)]

links = { a:[b] for a,b in tuples }
while True:
    toMerge = [(a,bs[-1]) for a,bs in links.items() if bs[-1] in links]
    for a,b in toMerge:
        links[a].append(b)
        del links[b]
    else: break
result = [ [a,*bs] for a,bs in links.items() ]
print(result)

# [[1909, 1910, 1910], [1935, 1922, 1922], [1940, 1939]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM