def toposorted(graph, parents):
 result = []
 used = set()
 def use(v, top):
  if (id(v) in used):
   return
  for parent in parents(v):
   if (parent is top):
    raise ValueError('graph is cyclical', graph)
   use(parent, v)
  used.add(id(v))
  result.append(v)
 for v in graph:
  use(v, v)
 return result

def toposorted ( graph , parents ) : result = [ ] used = set ( ) def use ( v , top ) : if ( id ( v ) in used ) : return for parent in parents ( v ) : if ( parent is top ) : raise ValueError ( 'graph is cyclical' , graph ) use ( parent , v ) used . add ( id ( v ) ) result . append ( v ) for v in graph : use ( v , v ) return result
returns vertices of a dag in topological order .