Please complete questions (3), (4), and (5) in the screenshot provided into the code given in the other screenshot. Given below is the implementations of dijkstras and bellman ford already completed. Python 3.10 or later def bellman_ford(self,s) : """Bellman Ford Algorithm for single source shortest path. Keyword Arguments: s - The source vertex. """ distances = {v: float('inf') for v in self.adjacency_list} distances[s] = 0 parents = {v: None for v in self.adjacency_list} for _ in range(len(self.adjacency_list) - 1): for from_vertex in self.adjacency_list: for to_vertex in self.adjacency_list[from_vertex]: if distances[from_vertex] + self.weights[(from_vertex, to_vertex)] < distances[to_vertex]: distances[to_vertex] = distances[from_vertex] + self.weights[(from_vertex, to_vertex)] parents[to_vertex] = from_vertex for from_vertex in self.adjacency_list: for to_vertex in self.adjacency_list[from_vertex]: if distances[from_vertex] + self.weights[(from_vertex, to_vertex)] < distances[to_vertex]: # Negative cycle found, return empty list return [] # No negative cycles found, return list of 3-tuples return [(v, distances[v], parents[v]) for v in distances] def dijkstra(self,s) : """Dijkstra's Algorithm using a binary heap as the PQ. Keyword Arguments: s - The source vertex. """ distance = [math.inf for x in self._adj] parent = [None for x in self._adj] Q = PQ() distance[s] = 0 Q.add(s, 0) S = [] for u in range(len(self._adj)): if u != s: Q.add(u, math.inf) while not Q.is_empty(): u = Q.extract_min() S.append(u) for v, w in self._adj[u].__iter__(True): if (distance[u] + w) < distance[v]: parent[v] = u distance[v] = (distance[u] + w) returnlist = [] for v in S: returnlist.append((v, distance[v], parent[v])) return returnlist

C++ Programming: From Problem Analysis to Program Design
8th Edition
ISBN:9781337102087
Author:D. S. Malik
Publisher:D. S. Malik
Chapter8: Arrays And Strings
Section: Chapter Questions
Problem 24PE
icon
Related questions
Question

Please complete questions (3), (4), and (5) in the screenshot provided into the code given in the other screenshot. Given below is the implementations of dijkstras and bellman ford already completed. Python 3.10 or later

 

def bellman_ford(self,s) :
        """Bellman Ford Algorithm for single source shortest path.

        Keyword Arguments:
        s - The source vertex.
        """
        distances = {v: float('inf') for v in self.adjacency_list}
        distances[s] = 0
        parents = {v: None for v in self.adjacency_list}

        for _ in range(len(self.adjacency_list) - 1):
            for from_vertex in self.adjacency_list:
                for to_vertex in self.adjacency_list[from_vertex]:
                    if distances[from_vertex] + self.weights[(from_vertex, to_vertex)] < distances[to_vertex]:
                        distances[to_vertex] = distances[from_vertex] + self.weights[(from_vertex, to_vertex)]
                        parents[to_vertex] = from_vertex

        for from_vertex in self.adjacency_list:
            for to_vertex in self.adjacency_list[from_vertex]:
                if distances[from_vertex] + self.weights[(from_vertex, to_vertex)] < distances[to_vertex]:
                    # Negative cycle found, return empty list
                    return []

        # No negative cycles found, return list of 3-tuples
        return [(v, distances[v], parents[v]) for v in distances]

 

def dijkstra(self,s) :
        """Dijkstra's Algorithm using a binary heap as the PQ.

        Keyword Arguments:
        s - The source vertex.
        """

        distance = [math.inf for x in self._adj]
        parent = [None for x in self._adj]
        Q = PQ()
        distance[s] = 0
        Q.add(s, 0)
        S = []
        for u in range(len(self._adj)):
            if u != s:
                Q.add(u, math.inf)
        while not Q.is_empty():
            u = Q.extract_min()
            S.append(u)
            for v, w in self._adj[u].__iter__(True):
                if (distance[u] + w) < distance[v]:
                    parent[v] = u
                    distance[v] = (distance[u] + w)
        returnlist = []
        for v in S:
            returnlist.append((v, distance[v], parent[v]))
        return returnlist       

 

(3) Implement
to do the following:
--
--
the time_shortest_path_algs function later in this file
--
Call random_weighted_graph tha I provided below
to generate a random weighted graph with 16 vertices and 120 edges
(i.e., completely connected--all possible undirected edges, other than loops)
and weights random in interval 1 to 10 inclusive.
Read documentation of time it (https://docs.python.org/3/library/timeit.html)
And also watch the videos I posted explaining its usage.
Use time it to time both Bellman-Ford and Dijkstra that you implemented
in steps 1 and 2 on this graph. I already imported the graphshw module
at the top.
The number parameter to timeit controls how many times the thing you're
timing is called.
To get meaningful times, you will need to experiment with this
a bit. E.g., increase it if the times are too small. Use the same
value of number for timing both algorithms.
IMPORTANT: Definitely don't use the default value of number, which is
something like 1000000 (e.g., the sun might explode before your program
finishes on the larger graphs below if you leave it at 10000000).
Make sure you don't include the time to generate the weighted graph in your
times.
Now repeat this for a graph with 64 vertices and 2016 edges.
Now repeat this for a graph with 256 vertices and 32640 edges.
Repeat this again for 16 vertices and 32 edges.
Repeat yet again with 64 vertices and 128 edges.
Repeat yet again with 256 vertices and 512 edges.
Have the time_shortest_path_algs function output the timing data in a
table, with columns for number of vertexes, number of edges, and time.
If you want, you can include larger graphs.
The pattern I used when indicating what size to use:
Dense graphs: v, e=v* (v-1)/2.
Sparse: v, e=2*v.
For example, if you want to continue the experimentation with
larger graphs, you might
try 1024 vertices with 523776 edges (dense graph),
1024 vertices with 2048 edges (sparse).
When you are timing the algorithms you can pass whatever vertex id you
want as the source vertex. It shouldn't affect the runtime by much,
if at all. The random weighted graphs are such that there exists paths
to any destination from any source, even the sparse graphs so timing
data shouldn't be affected much by source vertex.
4) Write some code in the if main block at the bottom of this file
to test that your Bellman-Ford and Dijkstra implementations work correctly.
I suggest constructing a WeightedGraph from one of the textbook examples
since you know the correct solution to those.
5) After that code, but in your if main block, call your function that
generates the timing data. Make sure you save that output to a text file.
If you run in IDLE, then just copy and paste from the shell into a text file.
If you run from the command line, you can just redirect the output to a text file.
Transcribed Image Text:(3) Implement to do the following: -- -- the time_shortest_path_algs function later in this file -- Call random_weighted_graph tha I provided below to generate a random weighted graph with 16 vertices and 120 edges (i.e., completely connected--all possible undirected edges, other than loops) and weights random in interval 1 to 10 inclusive. Read documentation of time it (https://docs.python.org/3/library/timeit.html) And also watch the videos I posted explaining its usage. Use time it to time both Bellman-Ford and Dijkstra that you implemented in steps 1 and 2 on this graph. I already imported the graphshw module at the top. The number parameter to timeit controls how many times the thing you're timing is called. To get meaningful times, you will need to experiment with this a bit. E.g., increase it if the times are too small. Use the same value of number for timing both algorithms. IMPORTANT: Definitely don't use the default value of number, which is something like 1000000 (e.g., the sun might explode before your program finishes on the larger graphs below if you leave it at 10000000). Make sure you don't include the time to generate the weighted graph in your times. Now repeat this for a graph with 64 vertices and 2016 edges. Now repeat this for a graph with 256 vertices and 32640 edges. Repeat this again for 16 vertices and 32 edges. Repeat yet again with 64 vertices and 128 edges. Repeat yet again with 256 vertices and 512 edges. Have the time_shortest_path_algs function output the timing data in a table, with columns for number of vertexes, number of edges, and time. If you want, you can include larger graphs. The pattern I used when indicating what size to use: Dense graphs: v, e=v* (v-1)/2. Sparse: v, e=2*v. For example, if you want to continue the experimentation with larger graphs, you might try 1024 vertices with 523776 edges (dense graph), 1024 vertices with 2048 edges (sparse). When you are timing the algorithms you can pass whatever vertex id you want as the source vertex. It shouldn't affect the runtime by much, if at all. The random weighted graphs are such that there exists paths to any destination from any source, even the sparse graphs so timing data shouldn't be affected much by source vertex. 4) Write some code in the if main block at the bottom of this file to test that your Bellman-Ford and Dijkstra implementations work correctly. I suggest constructing a WeightedGraph from one of the textbook examples since you know the correct solution to those. 5) After that code, but in your if main block, call your function that generates the timing data. Make sure you save that output to a text file. If you run in IDLE, then just copy and paste from the shell into a text file. If you run from the command line, you can just redirect the output to a text file.
def random_weighted_graph (v, e, min_w, max_w) :
"""Generates and returns a random weighted
graph with v vertices and e different edges.
Keyword arguments:
v number of vertices
e number of edges
if
min_w - minimum weight
max_w - maximum weight
edges = [ (random.randrange (0,1), i) for i in range (1, v) ]
# if desired number of edges greater than length of current edge list, then add more edges
if elen (edges) :
edgeSet = { x for x in edges }
not YetUsedEdges = [ (y,x) for x in range (1,v) for y in range (x) if (y,x) not in edgeSet]
random.shuffle (not YetUsedEdges)
count = e = len (edges)
count = min (count, len (not YetUsedEdges))
for i in range (count) :
#generate random edge weights
weights = [random.randint (min_w, max_w) for x in range (len (edges)) ]
edges.append (not YetUsedEdges.pop())
# construct a Digraph with the lists of edges and weights generated
G = WeightedGraph (v, edges, weights)
return G
def time_shortest_path_algs():
"""Generates a table of timing results comparing Dijkstra and Bellman-Ford."""
name
-
==
main":
#Here is where you write some code to test that your algorithms
#are correct.
#It is also where you will call your time_shortest_path_algs function.
#Don't forget to save output to a text file
Transcribed Image Text:def random_weighted_graph (v, e, min_w, max_w) : """Generates and returns a random weighted graph with v vertices and e different edges. Keyword arguments: v number of vertices e number of edges if min_w - minimum weight max_w - maximum weight edges = [ (random.randrange (0,1), i) for i in range (1, v) ] # if desired number of edges greater than length of current edge list, then add more edges if elen (edges) : edgeSet = { x for x in edges } not YetUsedEdges = [ (y,x) for x in range (1,v) for y in range (x) if (y,x) not in edgeSet] random.shuffle (not YetUsedEdges) count = e = len (edges) count = min (count, len (not YetUsedEdges)) for i in range (count) : #generate random edge weights weights = [random.randint (min_w, max_w) for x in range (len (edges)) ] edges.append (not YetUsedEdges.pop()) # construct a Digraph with the lists of edges and weights generated G = WeightedGraph (v, edges, weights) return G def time_shortest_path_algs(): """Generates a table of timing results comparing Dijkstra and Bellman-Ford.""" name - == main": #Here is where you write some code to test that your algorithms #are correct. #It is also where you will call your time_shortest_path_algs function. #Don't forget to save output to a text file
Expert Solution
steps

Step by step

Solved in 5 steps with 2 images

Blurred answer
Knowledge Booster
Polynomial time
Learn more about
Need a deep-dive on the concept behind this application? Look no further. Learn more about this topic, computer-science and related others by exploring similar questions and additional content below.
Similar questions
  • SEE MORE QUESTIONS
Recommended textbooks for you
C++ Programming: From Problem Analysis to Program…
C++ Programming: From Problem Analysis to Program…
Computer Science
ISBN:
9781337102087
Author:
D. S. Malik
Publisher:
Cengage Learning