Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python topological sort using lists indicating edges

Given lists: [1, 5, 6], [2, 3, 5, 6], [2, 5] etc. (not necessarily in any sorted order) such that if x precedes y in one list, then x precedes y in every list that have x and y, I want to find the list of all elements topologically sorted (so that x precedes y in this list if x precedes y in any other list.) There might be many solutions, in which case I want any of them.

What is the easiest way to implement this in Python.

like image 721
Neil G Avatar asked Nov 19 '11 12:11

Neil G


1 Answers

Here is a slightly simpler version of @unutbu's networkx solution:

import networkx as nx
data=[[1, 5, 6], [2, 3, 5, 6], [2, 5], [7]]
G = nx.DiGraph()
for path in data:
    G.add_nodes_from(path)
    G.add_path(path)
ts=nx.topological_sort(G)
print(ts)
# [7, 2, 3, 1, 5, 6]
like image 142
Aric Avatar answered Nov 13 '22 10:11

Aric