def TopologicallySorted(graph, get_edges):
 get_edges = memoize(get_edges)
 visited = set()
 visiting = set()
 ordered_nodes = []
 def Visit(node):
  if (node in visiting):
   raise CycleError(visiting)
  if (node in visited):
   return
  visited.add(node)
  visiting.add(node)
  for neighbor in get_edges(node):
   Visit(neighbor)
  visiting.remove(node)
  ordered_nodes.insert(0, node)
 for node in sorted(graph):
  Visit(node)
 return ordered_nodes

def TopologicallySorted ( graph , get_edges ) : get_edges = memoize ( get_edges ) visited = set ( ) visiting = set ( ) ordered_nodes = [ ] def Visit ( node ) : if ( node in visiting ) : raise CycleError ( visiting ) if ( node in visited ) : return visited . add ( node ) visiting . add ( node ) for neighbor in get_edges ( node ) : Visit ( neighbor ) visiting . remove ( node ) ordered_nodes . insert ( 0 , node ) for node in sorted ( graph ) : Visit ( node ) return ordered_nodes
topologically sort based on a user provided edge definition .