简体   繁体   English

用边指定为元组列表的图上的 DFS

[英]DFS on a graph specified with edges as list of tuples

I have a graph with its edges specified as a list of tuples.我有一个图,其边指定为元组列表。 Say, for example, we have:比如说,我们有:

edges = [('human', 'mammal'), ('mammal', 'vertebrate'), ('mouse', 'mammal'), ('vertebrate', 'animal')]

How would we write a method that recursively iterates over all the nodes that can be constructed from the above graph to perform a depth first search traversal in Python?我们如何编写一个递归迭代所有可以从上图中构造的节点的方法,以在 Python 中执行深度优先搜索遍历?

Any help is appreciated, thank you!任何帮助表示赞赏,谢谢!

This is a rather fun problem, which you should probably still try to solve yourself, but here's an example of an implementation:这是一个相当有趣的问题,您可能仍然应该尝试自己解决,但这里有一个实现示例:

from typing import Generator, Union


def construct(edges: list[tuple[str, str]]) -> dict:
    root = {}
    index = {}
    for x, isa in edges:
        if x in root:
            root[isa] = {x: root[x]}
            del root[x]
            index[isa] = root[isa]
        else:
            if x in index:
                raise SyntaxError(f'Invalid tree structure')
            if isa in index:
                index[isa][x] = (d := {})
            else:
                root[isa] = {x: (d := {})}
                index[isa] = root[isa]
            index[x] = d

    return root


def traverse(tree: Union[list[tuple[str, str]], dict]) -> Generator[str, None, None]:
    # this assumes that, if tree is a dict, it is a well-constructed tree, as construct() would return it
    if not isinstance(tree, dict):
        tree = construct(tree)

    for node in tree:
        yield node
        yield from traverse(tree[node])


def main():
    edges = [('human', 'mammal'), ('mammal', 'vertebrate'), ('mouse', 'mammal'), ('vertebrate', 'animal')]
    
    for node in traverse(edges):
        print(node)


if __name__  == '__main__':
    main()

This constructs a tree in linear time and then traverses it depth-first, yielding the visited nodes.这会在线性时间内构造一棵树,然后深度优先遍历它,产生访问过的节点。 It rejects trees that have duplicate leaf or node values, or cycles.它拒绝具有重复叶或节点值或循环的树。

Output:输出:

animal
vertebrate
mammal
human
mouse

My recommendation would be you give this example a try, try to understand it, and then write your own from scratch with whatever you learned.我的建议是你试试这个例子,试着理解它,然后用你学到的东西从头开始编写你自己的例子。

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

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