def topological_sort(graph, key=None):
 (V, E) = graph
 L = []
 S = set(V)
 E = list(E)
 for (v, u) in E:
  S.discard(u)
 if (key is None):
  key = (lambda value: value)
 S = sorted(S, key=key, reverse=True)
 while S:
  node = S.pop()
  L.append(node)
  for (u, v) in list(E):
   if (u == node):
    E.remove((u, v))
    for (_u, _v) in E:
     if (v == _v):
      break
    else:
     kv = key(v)
     for (i, s) in enumerate(S):
      ks = key(s)
      if (kv > ks):
       S.insert(i, v)
       break
     else:
      S.append(v)
 if E:
  raise ValueError('cycle detected')
 else:
  return L

def topological_sort ( graph , key = None ) : ( V , E ) = graph L = [ ] S = set ( V ) E = list ( E ) for ( v , u ) in E : S . discard ( u ) if ( key is None ) : key = ( lambda value : value ) S = sorted ( S , key = key , reverse = True ) while S : node = S . pop ( ) L . append ( node ) for ( u , v ) in list ( E ) : if ( u == node ) : E . remove ( ( u , v ) ) for ( _u , _v ) in E : if ( v == _v ) : break else : kv = key ( v ) for ( i , s ) in enumerate ( S ) : ks = key ( s ) if ( kv > ks ) : S . insert ( i , v ) break else : S . append ( v ) if E : raise ValueError ( 'cycle detected' ) else : return L
returns a depth first sorted order if depth_first is true .