Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

In Python: Graph class Implement an unweighted Graph using an adjacency matrix representation where the vertices are represented as rows and columns of a matrix

In Python:

Graph class

Implement an unweighted Graph using anadjacency matrixrepresentation where the vertices are represented as rows and columns of a matrix and the edges are represented by the cells at the intersection of the row and column vertices.

As part of the implementation, define a list to store vertices and a 2-dimensional numpy array to store edges. Define methods to add and remove vertices and edges to the graphs, and print the string representation of the graph.

Below is the list of fields and methods to be defined for the implementation:

  • Graph class:
    • Fields:
      • self.vert_list: list of all the vertices
      • self.adj_matrix: 2-dimensional matrix (numoy array) respresenting edges between the vertices.
    • Methods:
      • __init__(self): initializes the vert_list to an empty list, the and adj_matrix to an empty 2-D numpy array.
      • add_vertex(self, key): adds a vertex to the vert_list if it does not exist already. If the vertex exists in the vert_list, the list is not modified.
      • add_edge(self, v1, v2): adds an edge of weight 1 between vertices v1 and v2, as well as v2 and v1 in the adj_matrix. If either vertex is not present in the vert_list, the vertex is added to the vert_list, and then the edge is added to the adj_matrix.
      • __str__(self): retuns a string representation of the graph in the form: (v1, v2) (v1, v3) ... (vn, vn-1) The string representation should only show the edges that are present in the graph.

Main program

Define and call a main() function that uses the Graph class definition to create a Graph object. Create vertices and edges of the graph using Graph object methods. Print graph information using its string representation.

Here is a summary of main() function:

  • main() functipn:
    • create a graph object G
    • add sample data (vertices and edges) to the graph object G
    • print the string representation of the graph object G

You may use the sample data based on the graph shown below in your main function:

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Pro Android Graphics

Authors: Wallace Jackson

1st Edition

1430257857, 978-1430257851

More Books

Students also viewed these Programming questions