我们有一个类,它包含一个指向相同基类型的其他类的“依赖项”列表。
class Foo(Base):
dependencies = []
class Bar(Base):
dependencies = [Foo]
class Baz(Base):
dependencies = [Bar]
我们希望根据这些类生成的实例的依赖项对它们进行排序。在我们的示例中,我们希望 Foo 的实例排在第一位,然后是 Bar,最后是 Baz。
- 解决方案
解决这个问题的最好方法是使用拓扑排序。
拓扑排序是一种算法,它将有向无环图中的顶点排序,以便对于图中的每条边 e = (u, v),顶点 u 在顶点 v 之前出现。
拓扑排序的算法如下:
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
该算法首先找到所有没有依赖项的对象,并将它们放入队列中。然后,它反复从队列中取出一个对象,并将其作为结果输出。然后,它检查该对象的所有依赖项,如果它们都满足,则将它们放入队列中。如果某个对象的依赖项没有得到满足,则算法会产生一个错误。
一旦所有对象都从队列中取出,算法就会返回结果。结果是一个有序的对象列表,其中每个对象都按照其依赖关系排序。
另一方面,我们也可以将这个问题视为一个有向无环图 (DAG) 的拓扑排序问题。对于有向图,拓扑排序是一种将顶点排序的方法,使得对于图中的每条有向边 e = (u, v),顶点 u 在顶点 v 之前出现。
拓扑排序有许多不同的算法,其中一种最常见的算法是深度优先搜索 (DFS)。
深度优先搜索算法从图中的一个顶点开始,并沿着该顶点的所有边进行搜索。当算法到达一个死胡同时,它会回溯到上一个顶点,并继续沿着该顶点的所有边进行搜索。
当算法访问过图中的所有顶点后,它会返回一个拓扑排序结果。
from collections import deque
def topological_sort(graph):
"""
Perform a topological sort on a directed graph.
Args:
graph: A dictionary representing the graph, where the keys are the
vertices and the values are the edges.
Returns:
A list of the vertices in topological order.
"""
# Create a queue of vertices with no incoming edges.
queue = deque([vertex for vertex in graph if not graph[vertex]])
# Create a list to store the sorted vertices.
sorted_vertices = []
# While the queue is not empty, dequeue a vertex and add it to the
# sorted list.
while queue:
vertex = queue.popleft()
sorted_vertices.append(vertex)
# For each edge (vertex, neighbor) in the graph, if neighbor is
# not in the queue, add it to the queue.
for neighbor in graph[vertex]:
if neighbor not in queue:
queue.append(neighbor)
# If the sorted list is not the same length as the graph, then the
# graph contains a cycle.
if len(sorted_vertices) != len(graph):
raise ValueError("Graph contains a cycle.")
# Return the sorted list of vertices.
return sorted_vertices