Skip to content

Instantly share code, notes, and snippets.

@conceptofmind
Created January 17, 2025 14:53
Show Gist options
  • Save conceptofmind/3f3c71d8d1443c136112e98d009debb4 to your computer and use it in GitHub Desktop.
Save conceptofmind/3f3c71d8d1443c136112e98d009debb4 to your computer and use it in GitHub Desktop.
Toplogical Sort
def topological_sort_nx(files):
graphs = nx.DiGraph()
for file in files:
graphs.add_node(file)
for fileA in files:
for fileB in files:
if has_dependency(fileA, fileB):
graphs.add_edge(fileB, fileA)
# get disconnected graphs
subgraphs = list(nx.weakly_connected_components(graphs))
allResults = []
for subgraph in subgraphs:
results = []
subgraph_nodes = set(subgraph)
while len(results) != len(subgraph_nodes):
# 𝑓𝑖𝑙𝑒 ← argmin({π‘–π‘›π·π‘’π‘”π‘Ÿπ‘’π‘’[ 𝑓𝑖𝑙𝑒] | 𝑓𝑖𝑙𝑒 ∈ π‘ π‘’π‘π‘”π‘Ÿπ‘Žπ‘β„Ž and 𝑓𝑖𝑙𝑒 βˆ‰ π‘Ÿπ‘’π‘ π‘’π‘™π‘‘π‘ })
nodes = subgraph_nodes.difference(set(results))
file = min(
nodes,
key = lambda file: graphs.in_degree(file)
)
results.append(file)
allResults.append(results)
return allResults
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment