def topological_sort(graph):
    """
    Preforms a topological sort on the given graph. Code by Paul Harrison in
    the public domain.

    graph should be a dictionary mapping node names to lists of
    successor nodes.
    """

    # Count the occurrences of each node as a successor
    count = { }
    for node in graph:
        count[node] = 0
    for node in graph:
        for successor in graph[node]:
            count[successor] += 1

    # Get the 'root' nodes with no successors
    ready = [ node for node in graph if count[node] == 0 ]

    # Work through each root node
    result = [ ]
    while ready:
        # Grab a root node to work with
        node = ready.pop(-1)
        result.append(node)

        # Work through the successors for this node
        for successor in graph[node]:
            count[successor] -= 1
            if count[successor] == 0:
                ready.append(successor)

    return result