Sov*_*iut 8 python sorting dependencies
我有一个类,它有一个"依赖项"列表,指向同一基类型的其他类.
class Foo(Base):
dependencies = []
class Bar(Base):
dependencies = [Foo]
class Baz(Base):
dependencies = [Bar]
Run Code Online (Sandbox Code Playgroud)
我想根据它们的依赖关系对这些类生成的实例进行排序.在我的例子中,我希望Foo的实例首先出现,然后是Bar,然后是Baz.
排序这个的最佳方法是什么?
Die*_*Epp 18
它被称为拓扑排序.
def sort_deps(objs):
queue = [objs with no dependencies]
while queue:
obj = queue.pop()
yield obj
for obj in objs:
if dependencies are now satisfied:
queue.append(obj)
if not all dependencies are satisfied:
error
return result
Run Code Online (Sandbox Code Playgroud)
上周我有一个类似的问题 - 希望我知道Stack Overflow然后!我一直在寻找,直到我意识到我有一个DAG(有向无环图,因为我的依赖关系不能递归或循环).然后我找到了几个算法的引用来对它们进行排序.我使用深度优先遍历来获取叶节点并首先将它们添加到排序列表中.
这是我觉得有用的页面:
| 归档时间: |
|
| 查看次数: |
2480 次 |
| 最近记录: |