1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
| __all__ = ["TopologicalSorter", "CycleError"]
_NODE_OUT = -1 _NODE_DONE = -2
class _NodeInfo: __slots__ = "node", "npredecessors", "successors"
def __init__(self, node): self.node = node
self.npredecessors = 0
self.successors = []
class CycleError(ValueError): pass
class TopologicalSorter: def __init__(self, graph=None): self._node2info = {} self._ready_nodes = None self._npassedout = 0 self._nfinished = 0
if graph is not None: for node, predecessors in graph.items(): self.add(node, *predecessors)
def _get_nodeinfo(self, node): if (result := self._node2info.get(node)) is None: self._node2info[node] = result = _NodeInfo(node) return result
def add(self, node, *predecessors): """ node:当前节点 predecessors:依赖的节点 """ if self._ready_nodes is not None: raise ValueError("Nodes cannot be added after a call to prepare()")
nodeinfo = self._get_nodeinfo(node) nodeinfo.npredecessors += len(predecessors)
for pred in predecessors: pred_info = self._get_nodeinfo(pred) pred_info.successors.append(node)
def prepare(self): if self._ready_nodes is not None: raise ValueError("cannot prepare() more than once")
self._ready_nodes = [ i.node for i in self._node2info.values() if i.npredecessors == 0 ] cycle = self._find_cycle() if cycle: raise CycleError(f"nodes are in a cycle", cycle)
def get_ready(self): if self._ready_nodes is None: raise ValueError("prepare() must be called first")
result = tuple(self._ready_nodes) n2i = self._node2info for node in result: n2i[node].npredecessors = _NODE_OUT
self._ready_nodes.clear() self._npassedout += len(result) return result
def is_active(self): """如果可以取得更多进展,则返回' True ',否则返回' False '。 如果循环没有阻塞分辨率,或者仍然有节点准备就绪,“get_ready”还没有返回, 或者标记为“done”的节点数量小于“get_ready”返回的节点数量,则可以取得进展。 如果之前没有调用“prepare”而被调用,将引发ValueError。 """ if self._ready_nodes is None: raise ValueError("prepare() must be called first") return self._nfinished < self._npassedout or bool(self._ready_nodes)
def __bool__(self): return self.is_active()
def done(self, *nodes): if self._ready_nodes is None: raise ValueError("prepare() must be called first")
n2i = self._node2info
for node in nodes:
if (nodeinfo := n2i.get(node)) is None: raise ValueError(f"node {node!r} was not added using add()")
stat = nodeinfo.npredecessors if stat != _NODE_OUT: if stat >= 0: raise ValueError( f"node {node!r} was not passed out (still not ready)" ) elif stat == _NODE_DONE: raise ValueError(f"node {node!r} was already marked done") else: assert False, f"node {node!r}: unknown status {stat}"
nodeinfo.npredecessors = _NODE_DONE
for successor in nodeinfo.successors: successor_info = n2i[successor] successor_info.npredecessors -= 1 if successor_info.npredecessors == 0: self._ready_nodes.append(successor) self._nfinished += 1
def _find_cycle(self): n2i = self._node2info stack = [] itstack = [] seen = set() node2stacki = {}
for node in n2i: if node in seen: continue
while True: if node in seen: if node in node2stacki: return stack[node2stacki[node] :] + [node] else: seen.add(node) itstack.append(iter(n2i[node].successors).__next__) node2stacki[node] = len(stack) stack.append(node)
while stack: try: print(itstack[-1]) node = itstack[-1]() break except StopIteration: del node2stacki[stack.pop()] itstack.pop() else: break return None
def static_order(self): """ 按拓扑顺序返回节点的迭代对象 """ self.prepare() while self.is_active(): node_group = self.get_ready() yield from node_group self.done(*node_group)
if __name__ == '__main__': graph = { "C": ["A"], "B": ["A", "1"], "D": ["B", "C"], "E": ["B"], "F": ["D", "E"], } ts = TopologicalSorter(graph) ts.prepare()
read_node_flag = True while read_node_flag: read_node = ts.get_ready() if not read_node: read_node_flag = False break print(read_node) for x in read_node: ts.done(x)
|