forked from wjw12/python
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraphclass.py
More file actions
Latest commit
84 lines (72 loc) · 2.19 KB
/
Copy pathgraphclass.py
File metadata and controls
84 lines (72 loc) · 2.19 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
classGraph(object):
def__init__(self, graph_dict={}):
""" initializes a graph object """
self.__graph_dict=graph_dict
defvertices(self):
""" returns the vertices of a graph """
returnlist(self.__graph_dict.keys())
defedges(self):
""" returns the edges of a graph """
returnself.__generate_edges()
defadd_vertex(self, vertex):
""" If the vertex "vertex" is not in
self.__graph_dict, a key "vertex" with an empty
list as a value is added to the dictionary.
Otherwise nothing has to be done.
"""
ifvertexnotinself.__graph_dict:
self.__graph_dict[vertex] = []
defadd_edge(self, edge):
""" assumes that edge is of type set, tuple or list;
between two vertices can be multiple edges!
"""
edge=set(edge)
(vertex1, vertex2) =tuple(edge)
ifvertex1inself.__graph_dict:
self.__graph_dict[vertex1].append(vertex2)
else:
self.__graph_dict[vertex1] = [vertex2]
def__generate_edges(self):
""" A static method generating the edges of the
graph "graph". Edges are represented as sets
with one (a loop back to the vertex) or two
vertices
"""
edges= []
forvertexinself.__graph_dict:
forneighbourinself.__graph_dict[vertex]:
if {neighbour, vertex} notinedges:
edges.append({vertex, neighbour})
returnedges
def__str__(self):
res="vertices: "
forkinself.__graph_dict:
res+=str(k) +" "
res+="\nedges: "
foredgeinself.__generate_edges():
res+=str(edge) +" "
returnres
deffind_all_paths(self,start_vertex,end_vertex,path=[]):
graph=self.__graph_dict
path+=start_vertex
ifstart_vertex==end_vertex:
return [path]
ifstart_vertexnotingraph:
returnNone
paths_list= []
forvertexingraph[start_vertex]:
ifvertexnotinpath:
extended_paths=self.find_all_paths(vertex,end_vertex,path)
forpinextended_paths:
paths_list.append(p)
returnpaths_list
if__name__=="__main__":
g= { "a" : ["d"],
"b" : ["c"],
"c" : ["b", "c", "d", "e"],
"d" : ["a", "c"],
"e" : [],
"f" : []
}
graph=Graph(g)
print (graph.find_all_paths("a","e"))