首页 > 解决方案 > 如何遍历依赖图?

问题描述

我有需要根据一组规则执行的任务。

例如:

        | - File2
File1  -
        | - File3

这意味着File1的任务必须在File2和File3之前执行。我写了以下代码:

import json
    json_string = """
    {
        "file1": {
            "path_to_file": "file1.txt",
            "children": "file2,file3"
        },
        "file2": {
            "path_to_file": "file2.txt",
            "children": ""
        },
        "file3": {
            "path_to_file": "a/file3.txt",
            "children": ""
    }
"""


class Node(object):
    def __init__(self, name, path_to_file=None):
        self.name = name
        self.path_to_file = path_to_file
        self.children = []

    def add_child(self, obj):
        self.children.append(obj)

    def dump(self):
        print('%s' % (self.name))
        for obj in self.children:
            obj.dump()

name2info = json.loads(json_string)

def get_tree(name):
    info = name2info[name]
    root = Node(name, info['path_to_file'])
    for child in info['children'].split(","):
        if child:
            root.add_child(get_tree(child))
    return root

root = get_tree('file1')
root.dump()

这给了我:

file1
file2
file3

在此示例中,printexecution function节点中的。

问题是此代码不适用于以下情况:

File1  -
        | - File3
File2  -

如果我有:

   json_string = """
    {
        "file1": {
            "path_to_file": "file1.txt",
            "children": "file3"
        },
        "file2": {
            "path_to_file": "file2.txt",
            "children": "file3"
        },
        "file3": {
            "path_to_file": "a/file3.txt",
            "children": ""
    }

它会给我:

file1
file3
file2

它应该是:

file1
file2
file3   #3 is child of 1 and 2 - it can be executed only after 1 & 2 are done.

基本上,每个节点只有在它的所有父节点都完成了它们的执行功能(打印)后才能执行执行功能(打印)。我该如何解决这个问题?

标签: python

解决方案


你的依赖树实际上并不是一棵树——它是一个 DAG。当您在 处打印树时file1file2不应打印。

顺便说一句,您不应该将父级存储在 json 中,这将迫使您的系统成为一棵树。(这可能很好,取决于您的要求)


推荐阅读