2022-04-07 16:41:15 +02:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
|
|
|
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
# IMPORTS
|
|
|
|
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
2022-04-18 19:04:42 +02:00
|
|
|
from __future__ import annotations;
|
|
|
|
|
|
|
|
from src.local.typing import *;
|
2022-04-07 16:41:15 +02:00
|
|
|
|
|
|
|
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
# EXPORTS
|
|
|
|
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
__all__ = [
|
|
|
|
'Graph',
|
|
|
|
];
|
|
|
|
|
|
|
|
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
# CLASS Graph
|
|
|
|
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
class Graph(object):
|
|
|
|
'''
|
|
|
|
a data structure for graphs
|
|
|
|
'''
|
2022-04-18 19:04:42 +02:00
|
|
|
nodes: list[Any];
|
|
|
|
edges: list[tuple[Any,Any]]
|
2022-04-07 16:41:15 +02:00
|
|
|
|
2022-04-18 19:04:42 +02:00
|
|
|
def __init__(self, nodes: list[Any], edges: list[tuple[Any,Any]]):
|
2022-04-07 16:41:15 +02:00
|
|
|
self.nodes = nodes;
|
|
|
|
self.edges = edges;
|
|
|
|
return;
|
|
|
|
|
2022-04-18 19:04:42 +02:00
|
|
|
def __len__(self) -> int:
|
|
|
|
return len(self.nodes);
|
|
|
|
|
|
|
|
def subgraph(self, nodes: list[Any]) -> Graph:
|
|
|
|
'''
|
|
|
|
@returns graph induced by subset of nodes
|
|
|
|
'''
|
|
|
|
return Graph(
|
|
|
|
nodes = [ u for u in self.nodes if u in nodes ],
|
|
|
|
edges = [ (u, v) for u, v in self.edges if u in nodes and v in nodes ],
|
|
|
|
);
|
|
|
|
|
|
|
|
def successors(self, u: str):
|
2022-04-07 16:41:15 +02:00
|
|
|
'''
|
|
|
|
@returns
|
|
|
|
list of successor nodes
|
|
|
|
'''
|
|
|
|
return [ v for (u_, v) in self.edges if u == u_ ];
|
|
|
|
|
2022-04-18 19:04:42 +02:00
|
|
|
def predecessors(self, v: str):
|
2022-04-07 16:41:15 +02:00
|
|
|
'''
|
|
|
|
@returns
|
|
|
|
list of predecessor nodes
|
|
|
|
'''
|
|
|
|
return [ u for (u, v_) in self.edges if v == v_ ];
|