forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph.py
111 lines (90 loc) · 2.86 KB
/
graph.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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
"""
These are classes to represent a Graph and its elements.
It can be shared across graph algorithms.
"""
class Node:
"""
A node/vertex in a graph.
"""
def __init__(self, name):
self.name = name
@staticmethod
def get_name(obj):
"""
Return the name of the node
"""
if isinstance(obj, Node):
return obj.name
if isinstance(obj, str):
return obj
return''
def __eq__(self, obj):
return self.name == self.get_name(obj)
def __repr__(self):
return self.name
def __hash__(self):
return hash(self.name)
def __ne__(self, obj):
return self.name != self.get_name(obj)
def __lt__(self, obj):
return self.name < self.get_name(obj)
def __le__(self, obj):
return self.name <= self.get_name(obj)
def __gt__(self, obj):
return self.name > self.get_name(obj)
def __ge__(self, obj):
return self.name >= self.get_name(obj)
def __bool__(self):
return self.name
class DirectedEdge:
"""
A directed edge in a directed graph.
Stores the source and target node of the edge.
"""
def __init__(self, node_from, node_to):
self.source = node_from
self.target = node_to
def __eq__(self, obj):
if isinstance(obj, DirectedEdge):
return obj.source == self.source and obj.target == self.target
return False
def __repr__(self):
return f"({self.source} -> {self.target})"
class DirectedGraph:
"""
A directed graph.
Stores a set of nodes, edges and adjacency matrix.
"""
# pylint: disable=dangerous-default-value
def __init__(self, load_dict={}):
self.nodes = []
self.edges = []
self.adjacency_list = {}
if load_dict and isinstance(load_dict, dict):
for vertex in load_dict:
node_from = self.add_node(vertex)
self.adjacency_list[node_from] = []
for neighbor in load_dict[vertex]:
node_to = self.add_node(neighbor)
self.adjacency_list[node_from].append(node_to)
self.add_edge(vertex, neighbor)
def add_node(self, node_name):
"""
Add a new named node to the graph.
"""
try:
return self.nodes[self.nodes.index(node_name)]
except ValueError:
node = Node(node_name)
self.nodes.append(node)
return node
def add_edge(self, node_name_from, node_name_to):
"""
Add a new edge to the graph between two nodes.
"""
try:
node_from = self.nodes[self.nodes.index(node_name_from)]
node_to = self.nodes[self.nodes.index(node_name_to)]
self.edges.append(DirectedEdge(node_from, node_to))
except ValueError:
pass