代码之家  ›  专栏  ›  技术社区  ›  Soviut

如何根据依赖项进行排序?

  •  8
  • Soviut  · 技术社区  · 15 年前

    我有一个类,它有一个“依赖项”列表,指向同一基类型的其他类。

    class Foo(Base):
        dependencies = []
    
    class Bar(Base):
        dependencies = [Foo]
    
    class Baz(Base):
        dependencies = [Bar]
    

    我想对这些类根据其依赖性生成的实例进行排序。在我的例子中,我希望foo的实例首先出现,然后是bar,然后是baz。

    最好的分类方法是什么?

    2 回复  |  直到 15 年前
        1
  •  18
  •   Dietrich Epp    15 年前

    它被称为拓扑类。

    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
    
        2
  •  5
  •   Tony Tanzillo    15 年前

    上周我也遇到过类似的问题——希望我能知道堆栈溢出的情况!我四处搜寻,直到我意识到我有一个 达格 (定向的 无环的 因为我的依赖关系不能是递归的或循环的)。然后我找到了一些算法排序的参考资料。我使用深度优先遍历来获取叶节点,并首先将它们添加到排序列表中。

    以下是我发现有用的页面:

    Directed Acyclic Graphs