-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph.py
More file actions
67 lines (52 loc) · 1.84 KB
/
graph.py
File metadata and controls
67 lines (52 loc) · 1.84 KB
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
import graph_types
class Builder(graph_types.BuilderType):
"""Builder for an immutable graph."""
def __init__(self, factory):
"""Construct a graph builder.
:param factory: Factory instance to use to build the graph. (e.g.,
basic_graph.Factory())
:return: a graph builder for the specified factory type.
"""
self._factory = factory
self._nodes = {}
self._edges = {}
# @Override
def node(self, node_id):
if node_id in self._nodes:
return self._nodes[node_id]
node = self._factory.create_node(node_id)
self._nodes[node_id] = node
return node
# @Override
def edge(self, start_node_id, end_node_id):
key = (start_node_id, end_node_id)
if key in self._edges:
return self._edges[key]
start_node = self.node(start_node_id)
end_node = self.node(end_node_id)
edge = self._factory.create_edge(start_node, end_node)
self._edges[key] = edge
return edge
# @Override
def build(self):
nodes = self._nodes.values()
edges = self._edges.values()
return self._factory.create_graph(nodes, edges)
def from_string(factory, str_graph):
"""Construct a graph from a string specifier.
"A->B->C, B->C, D -> E, E -> F, G, H"
:param factory graph factory instance to use to construct graph.
:param str_graph string describing graph to construct.
:return: a graph.
"""
builder = Builder(factory)
node_sequences = [s.split('->') for s in str_graph.split(",")]
for seq in node_sequences:
last_id = None
for s in seq:
node_id = s.strip()
builder.node(node_id)
if last_id is not None:
builder.edge(last_id, node_id)
last_id = node_id
return builder.build()