python 拓扑排序正确版

tech2024-01-26  73

def indegree0(v, e): if v == []: return None tmp = v[:] for i in e: if i[1] in tmp: tmp.remove(i[1]) if tmp == []: return -1 for t in tmp: for i in range(len(e)): if t in e[i]: e[i] = 'toDel' # 占位,之后删掉 if e: eset = set(e) eset.remove('toDel') e[:] = list(eset) if v: for t in tmp: v.remove(t) return tmp def topoSort(v, e): result = [] while True: nodes = indegree0(v, e) if nodes == None: break if nodes == -1: print('there\'s a circle.') return None result.append(nodes) return result if __name__ == '__main__': v = ['v1', 'v2', 'v3', 'v4', 'v5',"v6","v7"] e = [('v1', 'v2'),('v1', 'v3'),('v1', 'v4'),('v2', 'v5'),('v2', 'v6'),('v3', 'v5'),('v3', 'v6'),('v4', 'v6'),('v5', 'v7'),('v6', 'v7')] res = topoSort(v, e) print(res)
最新回复(0)