python - 如何遍历依赖图?
问题描述
我有需要根据一组规则执行的任务。
例如:
| - 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
在此示例中,print
是execution 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.
基本上,每个节点只有在它的所有父节点都完成了它们的执行功能(打印)后才能执行执行功能(打印)。我该如何解决这个问题?
解决方案
你的依赖树实际上并不是一棵树——它是一个 DAG。当您在 处打印树时file1
,file2
不应打印。
顺便说一句,您不应该将父级存储在 json 中,这将迫使您的系统成为一棵树。(这可能很好,取决于您的要求)
推荐阅读
- php - 如何使用PHP根据类别计算分数
- email - 使用谷歌应用脚本获取 gmail 中的当前线程 ID
- ios - ionic 3 cordova ios build failed 'google/protobuf/Api.pbobjc.h' 文件未找到
- email - Jenkins - 如何在 FxCop 报告中发送包含警告和问题的电子邮件
- python - 遍历 pandas 系列
- r - 对相似列求和
- python - 针对 2 测试 Python 方法
- javascript - JavaScript 表单验证自定义消息和最小字段长度
- javascript - Angularjs - 如何使用解析器重定向到另一个状态
- c# - C# Sqlite '约束失败'