Modifying topological sort in python