Skip to content

Instantly share code, notes, and snippets.

@sidsbrmnn
Created January 10, 2024 00:24
Show Gist options
  • Select an option

  • Save sidsbrmnn/29c82d5b79bc62630980ea12ddb64ac3 to your computer and use it in GitHub Desktop.

Select an option

Save sidsbrmnn/29c82d5b79bc62630980ea12ddb64ac3 to your computer and use it in GitHub Desktop.
Dependency graph sorter
from collections import defaultdict
from itertools import chain
class Graph:
def __init__(self, vertices: list[str]):
self._graph = defaultdict(list)
self._V = vertices
def add_edge(self, u: str, v: str):
self._graph[u].append(v)
def _sort(self, v: str, visited: dict[str, bool], stack: list[str]):
visited[v] = True
for i in self._graph[v]:
if visited[i] == False:
self._sort(i, visited, stack)
stack.append(v)
def sort(self):
visited = {i: False for i in self._V}
stack: list[str] = []
for i in self._V:
if visited[i] == False:
self._sort(i, visited, stack)
return stack
dependencies = {
"apr-util": ["apr", "expat", "openldap", "openssl"],
"cracklib": ["zlib"],
"curl": ["nghttp2", "openldap", "openssl", "zlib"],
"cyrus-sasl": ["openssl", "zlib"],
"httpd": ["apr", "apr-util", "libxml2", "nghttp2", "openssl", "pcre", "zlib"],
"libxslt": ["libxml2"],
"mysql": ["cracklib", "openssl", "ncurses", "zlib"],
"openldap": ["cyrus-sasl", "openssl"],
"openssl": ["zlib"],
"pcre": ["readline"],
"perl": ["zlib"],
"php": ["curl", "cyrus-sasl", "httpd", "icu", "libxml2", "libxslt", "mysql", "openldap", "openssl", "pcre", "zlib"],
"python": ["expat", "libffi", "ncurses", "openssl", "readline", "zlib"],
"readline": ["ncurses"],
}
packages = list(set(chain.from_iterable([[k] + v for k, v in dependencies.items()])))
# packages.sort()
graph = Graph(packages)
for key, values in dependencies.items():
for value in values:
graph.add_edge(key, value)
print(graph.sort())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment