~bzr-pqm/bzr/bzr.dev

1185.16.113 by mbp at sourcefrog
Add topo_sort utility function
1
# (C) 2005 Canonical
2
#
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
17
import pdb
18
1185.16.114 by mbp at sourcefrog
Improved topological sort
19
from bzrlib.errors import GraphCycleError
20
21
def topo_sort(graph):
1185.16.113 by mbp at sourcefrog
Add topo_sort utility function
22
    """Topological sort a graph.
23
1185.16.114 by mbp at sourcefrog
Improved topological sort
24
    graph -- sequence of pairs of node->parents_list.
25
26
    The result is a list of node names, such that all parents come before
27
    their children.
28
29
    Nodes at the same depth are returned in sorted order.
1185.16.113 by mbp at sourcefrog
Add topo_sort utility function
30
31
    node identifiers can be any hashable object, and are typically strings.
32
    """
33
    parents = {}  # node -> list of parents
34
    children = {} # node -> list of children
1185.16.114 by mbp at sourcefrog
Improved topological sort
35
    for node, node_parents in graph:
36
        assert node not in parents, \
37
            ('node %r repeated in graph' % node)
38
        parents[node] = set(node_parents)
39
        if node not in children:
40
            children[node] = set()
41
        for parent in node_parents:
42
            if parent in children:
43
                children[parent].add(node)
44
            else:
45
                children[parent] = set([node])
1185.16.113 by mbp at sourcefrog
Add topo_sort utility function
46
    result = []
47
    while parents:
48
        # find nodes with no parents, and take them now
1185.16.114 by mbp at sourcefrog
Improved topological sort
49
        no_parents = [n for n in parents if len(parents[n]) == 0]
50
        no_parents.sort()
51
        if not no_parents:
52
            raise GraphCycleError(parents)
53
        for n in no_parents:
1185.16.113 by mbp at sourcefrog
Add topo_sort utility function
54
            result.append(n)
55
            for child in children[n]:
56
                assert n in parents[child]
57
                parents[child].remove(n)
58
            del children[n]
59
            del parents[n]
60
    return result