forked from intel/he-toolkit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtsort.py
35 lines (26 loc) · 933 Bytes
/
tsort.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# Copyright (C) 2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""Module providing a topological sort"""
from typing import Set, Any
class CycleError(Exception):
"""Error for indicating a cycle found in an DAG"""
def tsort(G: dict):
"""Topological sort of graph G"""
# Following Python 3.9 TopologicalSorter.static_order();
# The dict values are the nodes pointing to the keys.
def dfs(node, path):
"""Recursive generator. Depth first search."""
if len(path) > 1 and path[0] == path[-1]:
raise CycleError(f"cycle:{path}")
if node in visited:
return
visited.add(node)
try:
for next_node in G[node]:
yield from dfs(next_node, [*path, next_node])
except KeyError:
pass
yield node
visited: Set[Any] = set()
for node in G.keys():
yield from dfs(node, [node])