code: def topological_sorting(nodes, relations):
      '''An implementation of Kahn's algorithm.
      '''
      ret = []
      nodes = set(nodes) | _nodes(relations)
      inc = _incoming(relations)
      out = _outgoing(relations)
      free = _free_nodes(nodes, inc)
      while free:
          n = free.pop()
          ret.append(n)
          out_n = list(out[n])
          for m in out_n:
              out[n].remove(m)
              inc[m].remove(n)
              if _is_free(m, inc):
                  free.add(m)
      if not all(_is_free(node, inc) and _is_free(node, out) for node in nodes):
          raise ValueError("Cycle detected")
      return ret