def reps_toposort(r):
 r = sympify(r)
 E = []
 for (c1, (k1, v1)) in enumerate(r):
  for (c2, (k2, v2)) in enumerate(r):
   if (k1 in v2.free_symbols):
    E.append((c1, c2))
 return [r[i] for i in topological_sort((range(len(r)), E))]

def reps_toposort ( r ) : r = sympify ( r ) E = [ ] for ( c1 , ( k1 , v1 ) ) in enumerate ( r ) : for ( c2 , ( k2 , v2 ) ) in enumerate ( r ) : if ( k1 in v2 . free_symbols ) : E . append ( ( c1 , c2 ) ) return [ r [ i ] for i in topological_sort ( ( range ( len ( r ) ) , E ) ) ]
sort replacements r so appears before if k2 is in v1s free symbols .