Lab 4 SP Solution 02052023 042711pm
Lab 4 SP Solution 02052023 042711pm
CSL 411
LAB JOURNAL 4
CODE
graph = {'A': ['B', 'C'],
'C': ['D','F'],
'D': ['C','E'],
'E': ['F'],
'F': ['C','E']}
if src == destination:
return [path]
paths = []
new_path_list = []
paths.append(new_path)
return paths
def find_shortest_path(graph, start, target, path=[]):
if start == target:
return path
return None
shortest_path = None
if newpath:
shortest_path = newpath
return shortest_path
print(path)
shortest = find_shortest_path(graph,'A','F')
OUTPUT
2. Consider a simple (directed) graph (digraph) having six nodes (A-F) and the following arcs
(directed edges) with respective cost of edge given in parentheses:
A -> B (2)
A -> C (1)
B -> C (2)
B -> D (5)
C -> D (1)
C -> F (3)
D -> C (1)
D -> E (4)
E -> F (3)
F -> C (1)
F -> E (2)
Using the code for a directed weighted graph in Example 2, instantiate an object of DWGraph in
__main__, add the nodes and edges of the graph using the relevant functions, and implement a function
find_path() that takes starting and ending nodes as arguments and returns at least one path (if one exists)
between those two nodes. The function should also keep track of the cost of the path and return the total
cost as well as the path. Print the path and its cost in __main__.
Code
class Graph:
Args:
"""
def length(self):
>>> len(g)
"""
return len(self.nodes)
def traverse(self):
if n not in self.nodes:
self.nodes.append(n)
self.adj[n] = []
def number_of_nodes(self):
return len(self.nodes)
def number_of_edges(self):
class DGraph(Graph):
class WGraph(Graph):
Args:
"""
self.nodes, self.adj, self.weight = [], {}, {}
self.weight[(u,v)] = w
self.weight[(v,u)] = w
return self.weight[(u,v)]
class DWGraph(WGraph):
self.weight[(u,v)] = w
newpath=None
path=path+[start]
if start == end:
return path,cost
return None,cost
for node in self.adj[start]:
if newpath!=None:
return newpath,cost
dw=DWGraph()
dw.add_node('A')
dw.add_node('B')
dw.add_node('C')
dw.add_node('D')
dw.add_node('F')
dw.add_edge('A','B',2)
dw.add_edge('A','C',1)
dw.add_edge('B','C',2)
dw.add_edge('B','D',5)
dw.add_edge('C','D',1)
dw.add_edge('C','F',3)
dw.add_edge('D','C',1)
dw.add_edge('D','E',4)
dw.add_edge('E','F',3)
dw.add_edge('F','C',1)
dw.add_edge('F','E',2)
print(dw.traverse(),'\n')
print(dw.find_path('A', 'F'))
Output