×
Samples Blogs Make Payment About Us Reviews 4.9/5 Order Now

Program To Process an Undirected Graph in Python Assignment Solution

July 08, 2024
Prof. Emily Wong
Prof. Emily
🇨🇦 Canada
Python
Prof. Emily Wong, with a Master's degree in Computer Science from the University of Sydney, has completed over 600 Python programming test assignments. She specializes in Python topics such as data visualization, web scraping, natural language processing, and game development.
Key Topics
  • Instructions
  • Requirements and Specifications
Tip of the day
Use Python libraries effectively by importing only what you need. For example, if you're working with data, using libraries like pandas and numpy can save time and simplify complex tasks like data manipulation and analysis.
News
In 2024, the Biden-Harris Administration has expanded high-dosage tutoring and extended learning programs to boost academic achievement, helping programming students and others recover from pandemic-related setbacks. These initiatives are funded by federal resources aimed at improving math and literacy skills​

Instructions

Objective

Write a python assignment program to process an undirected graph.

Requirements and Specifications

Introduction

NetworkX is a Python library for graph processing. Recall that an undirected graph is a set of vertices (which may contain labels) and a set of edges (which may contain weights) that connect a subset of those vertices together.

To write a python homework, you can build a design and implement a Graph class that:

  1. Keeps track of the current number of edges in the graph.
  2. Keeps a 10x10 adjacency matrix using a 2-D NumPy array initially containing all zeros. The entries in the ith row and jth column and the jth row and ith column are set to 1 if an edge exists between node i and node j.
  3. Has a method add_edge() that takes two vertices (integers from 0-9) and sets the (i, j) and (j, i) entries of the adjacency matrix to 1 and updates the edge count.
  4. Has a method degree() that takes a vertex (an integer from 0-9) and returns its degree (the number of edges incident to that vertex) Your main() method should use a while loop to prompt a user to input an edge (a pair of integers from 0-9 separated by a space, ex: "3 8") until a user enters a "q" to quit the program. Each time a valid pair of vertices is entered by the user you should add the edge to the graph by updating the adjacency matrix and update its edge count. Once the user requests to exit the program, your code should output the degree of all vertices (including zeros for nodes that technically weren't inserted). Your code should also handle (raise and except) input errors in two ways using custom exception classes:

If the user provides an integer that is not between 0 and 9, raise a "VertexOutOfBoundsException" and handle it by printing "Vertex out of bounds." and a 'pass' statement and prompt the user again.

If the user provides a single integer, rather than a pair, raise a "SelfLoopException" and handle it by printing "Self-loops are not permitted." and a 'pass' statement and prompt the user again.

Source Code

import networkx as nx import numpy as np class VertexOutOfBoundsException(Exception): pass class SelfLoopException(Exception): pass class Graph(object): def __init__(self): self.size = 10 self.adj = np.zeros((self.size, self.size)) self.edge_count = np.zeros(self.size) def add_edge(self, i, j): if i < 0 or i >= self.size: raise VertexOutOfBoundsException if j < 0 or j >= self.size: raise VertexOutOfBoundsException if i == j: raise SelfLoopException if self.adj[i,j] == 0: self.adj[i,j] = 1 self.adj[j,i] = 1 self.edge_count[i] += 1 self.edge_count[j] += 1 def degree(self, i): if i < 0 or i >= self.size: raise VertexOutOfBoundsException return self.edge_count[i] def __str__(self): output = '' for i in range(self.size): output += 'Degree of vertex ' + str(i) + ': ' + str(self.degree(i)) + '\n' return output def main(): g = Graph() while True: s = input('Please, enter edge to add to graph: ') parts = s.split(" ") if parts[0].lower() == 'q': break try: g.add_edge(int(parts[0]), int(parts[1])) except VertexOutOfBoundsException: print("Vertex out of bounds.") pass except SelfLoopException: print("Self-loops are not permitted.") pass print(g) if __name__ == "__main__": main()

Related Samples

Unlock our free Python assignment samples to enhance your coding skills. These examples provide clear, detailed solutions, helping you grasp complex concepts and excel in your assignments. Access these resources to boost your understanding and achieve academic success.