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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With