[issue17005] Add a topological sort algorithm
Gareth Rees
report at bugs.python.org
Fri Jan 18 16:09:37 EST 2019
Gareth Rees <gdr at garethrees.org> added the comment:
Just to elaborate on what I mean by "bug magnet". (I'm sure Pablo understands this, but there may be other readers who would like to see it spelled out.)
Suppose that you have a directed graph represented as a mapping from a vertex to an iterable of its out-neighbours. Then the "obvious" way to get a total order on the vertices in the graph would be to generate the edges and pass them to topsort:
def edges(graph):
return ((v, w) for v, ww in graph.items() for w in ww)
order = topsort(edges(graph))
This will appear to work fine if it is never tested with a graph that has isolated vertices (which would be an all too easy omission).
To handle isolated vertices you have to remember to write something like this:
reversed_graph = {v: [] for v in graph}
for v, ww in graph.items():
for w in ww:
reversed_graph[w].append(v)
order = topsort(edges(graph)) + [
v for v, ww in graph.items() if not ww and not reversed_graph[v]]
I think it likely that beginner programmers will forget to do this and be surprised later on when their total order is missing some of the vertices.
----------
_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue17005>
_______________________________________
More information about the Python-bugs-list
mailing list