-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraph.py
More file actions
134 lines (105 loc) · 3.52 KB
/
Graph.py
File metadata and controls
134 lines (105 loc) · 3.52 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
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
""" Code example from Complexity and Computation, a book about
exploring complexity science with Python. Available free from
http://greenteapress.com/complexity
Copyright 2011 Allen B. Downey.
Distributed under the GNU General Public License at gnu.org/licenses/gpl.html.
"""
class Vertex(object):
"""A Vertex is a node in a graph."""
def __init__(self, label=''):
self.label = label
def __repr__(self):
"""Returns a string representation of this object that can
be evaluated as a Python expression."""
return 'Vertex(%s)' % repr(self.label)
__str__ = __repr__
"""The str and repr forms of this object are the same."""
class Edge(tuple):
"""An Edge is a list of two vertices."""
def __new__(cls, *vs):
"""The Edge constructor takes two vertices."""
if len(vs) != 2:
raise ValueError, 'Edges must connect exactly two vertices.'
return tuple.__new__(cls, vs)
def __repr__(self):
"""Return a string representation of this object that can
be evaluated as a Python expression."""
return 'Edge(%s, %s)' % (repr(self[0]), repr(self[1]))
__str__ = __repr__
"""The str and repr forms of this object are the same."""
class Graph(dict):
"""A Graph is a dictionary of dictionaries. The outer
dictionary maps from a vertex to an inner dictionary.
The inner dictionary maps from other vertices to edges.
For vertices a and b, graph[a][b] maps
to the edge that connects a->b, if it exists."""
def __init__(self, vs=[], es=[]):
"""Creates a new graph.
vs: list of vertices;
es: list of edges.
"""
for v in vs:
self.add_vertex(v)
for e in es:
self.add_edge(e)
def add_vertex(self, v):
"""Add a vertex to the graph."""
self[v] = {}
def add_edge(self, e):
"""Adds and edge to the graph by adding an entry in both directions.
If there is already an edge connecting these Vertices, the
new edge replaces it.
"""
v, w = e
self[v][w] = e
self[w][v] = e
def get_edge(self, v, w):
try:
return self[v][w]
except:
return None
def remove_edge(self, e):
v, w = e
try:
del(self[v][w])
del(self[w][v])
except:
print("The edge doesn't exist")
def vertices(self):
return [key for key, value in self.items()]
def edges(self):
edge_list = []
if len(self) > 2:
for key, value in self.items():
for vertex, edge in value.items():
if edge not in edge_list:
edge_list.append(edge)
return edge_list
def out_vertices(self, v):
[(vertex, edge)] = self[v].items()
return vertex
def out_edges(self, v):
[(vertex, edge)] = self[v].items()
return edge
def add_all_edges(self):
for v in self.vertices():
other_verts = [x for x in self.vertices() if x != v]
for vertex in other_verts:
self.add_edge(Edge(v, vertex))
def main(script, *args):
v = Vertex('v')
print v
w = Vertex('w')
print w
e = Edge(v, w)
print e
g = Graph([v,w], [e])
print g
test_edge = g.get_edge(v,w)
print g.vertices()
print g.edges()
print g.out_vertices(v)
print g.out_edges(v)
if __name__ == '__main__':
import sys
main(*sys.argv)