Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Node:
- def __init__(self, name):
- self.name = name
- self.nb = []
- self.visited = False
- def __str__(self):
- return self.name
- class Graph:
- def __init__(self):
- self.nodes = []
- self.sorted = []
- def topological_sort(self):
- self.sorted.clear()
- for n in self.nodes:
- self.__visit(n)
- def __visit(self, node):
- if node.visited: return
- node.visited = True
- for n in node.nb:
- self.__visit(n)
- self.sorted.append(node)
- a = Node('A')
- b = Node('B')
- c = Node('C')
- d = Node('D')
- e = Node('E')
- f = Node('F')
- g = Node('G')
- h = Node('H')
- i = Node('I')
- j = Node('J')
- a.nb[:] = [b, f]
- b.nb[:] = [h]
- d.nb[:] = [c, e, i]
- e.nb[:] = [i]
- g.nb[:] = [a, b, c]
- i.nb[:] = [c]
- j.nb[:] = [e]
- G = Graph()
- G.nodes[:] = [a, b, c, d, e, f, g, h, i, j]
- G.topological_sort()
- print([str(n) for n in reversed(G.sorted)])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement