Question

In: Computer Science

in python programming language, please include the proper identation This homework will allow you to demonstrate...

in python programming language, please include the proper identation

This homework will allow you to demonstrate understanding and engagement with the following topics:

graph representations

object oriented programming

graph processing,such as finding shortest paths and finding tree traversals

Your task is to implement a Graph class. The edges in the graph are undirected, but you must implement an Edge class. In addition, you will have a Graph class, and a Node class. You can choose to implement graphs with any of the four implementation methods.

init

insertNode(d) : takes data contained as its argument, and adds it into the graph, after putting the data element into a node

deleteNode(d): finds a node with data d in its node, and deletes it. Also deletes all edges from and into it. Prints an error message if no such node exists.

insertEdge(a, b, w, name): Inserts a new edge between node with data a and node with data b. The edge has name name, and weight w. Prints an error message if either of those nodes does not exist.

deleteEdge(a,b): Deletes the edge between a node with data a and a node with data b. Prints an error message if no such edge exists.

FindPath(a,b): Prints the shortest path from node with data a to node with data b, found by using Dijkstra's algorithm. The printing of the path includes printing the nodes which are part of the path, as well as printing the name and weight of each of the edges. Nodes and edges are printed in the order in which they are part of the path. Finally, prints the total weight of the path. Prints an error message if the path does not exist.

FindSpanningTree(n): uses Kruskal's algorithm to find a spanning tree rooted on node n. The printing of the tree includes printing the nodes which are part of the tree, as well as printing the name and weight of each of the edges. Prints an error message if the spanning tree does not exist (that is, if the algorithm runs out of edges, and there are still two or more groups of nodes that have not been merged.

Solutions

Expert Solution

class Graph:
# Dictionary containing keys that map to the corresponding vertex object
def __init__(own):   
own.vertices = {}

# Adds a vertex with the given key to the graph.
def addVertex(own, keyValue):   
vertex = Vertex(keyValue)
own.vertices[keyValue] = vertex

# Returns vertex object with the corresponding key value.
def getVertex(own, keyValue):   
return own.vertices[keyValue]

def __contains__(own, keyValue):
return keyValue in own.vertices

# Adds an edge from sourceKey to destinationKey with given weight in the graph.
def addEdge(own, sourceKey, destinationKey, weight = 1):   
own.vertices[sourceKey].addNeighbour(own.vertices[destinationKey], weight)

# Returns True if there is an edge from sourceKey to destinationKey in the graph
def edgeExist(own, sourceKey, destinationKey):   
return own.vertices[sourceKey].isPointToDestination(own.vertices[destinationKey])

def __iter__(own):
return iter(own.vertices.values())


class Vertex:
def __init__(own, keyValue):
own.key = keyValue
own.pointingTo = {}

# Returns key corresponding to this vertex object.
def getKey(own):   
return own.key

# Make this vertex point to destination with given edge weight.
def addNeighbour(own, destination, weight):   
own.pointingTo[destination] = weight

# Returns all vertices pointed to by this vertex.
def getNeighbours(own):   
return own.pointingTo.keys()

# Gets the weight of edge from this vertex to destination
def getWeight(own, destination):   
return own.pointingTo[destination]

# Returns True if this vertex points to destination
def isPointToDestination(own, destination):   
return destination in own.pointingTo


def dijkstraAlgorithm(graph, sourceNode):
"""Return distance where distance[v] is min distance from source to v.
This will return a dictionary distance.
graph is a Graph object.
source is a Vertex object in g."""
unvisitedNode = set(graph)
currentDistance = dict.fromkeys(graph, float('inf'))
currentDistance[sourceNode] = 0

while unvisitedNode != set():
# Search for vertex with minimum distance
closest = min(unvisitedNode, key = lambda v: currentDistance[v])

# Marks the node as visited node
unvisitedNode.remove(closest)

# Update the distances
for neighbour in closest.getNeighbours():
if neighbour in unvisitedNode:
newDistance = currentDistance[closest] + closest.getWeight(neighbour)
if currentDistance[neighbour] > newDistance:
currentDistance[neighbour] = newDistance

return currentDistance


grh = Graph()
print('Undirected Graph')
print('Menu')
print('Add vertex <key>')
print('Add edge <src> <dest> <weight>')
print('Shortest <source vertex key>')
print('Show')
print('EXIT')

while True:
do = input('Enter your choice: ').split()

choice = do[0]
if choice == 'Add':
subChoice = do[1]
if subChoice == 'vertex':
keyValue = int(do[2])
if keyValue not in grh:
grh.addVertex(keyValue)
else:
print('Vertex already exists in the graph.')
elif subChoice == 'edge':
src = int(do[2])
dest = int(do[3])
weight = int(do[4])
if src not in grh:
print('Vertex {} does not exist in the graph.'.format(src))
elif dest not in grh:
print('Vertex {} does not exist in the graph.'.format(dest))
else:
if not grh.edgeExist(src, dest):
grh.addEdge(src, dest, weight)
grh.addEdge(dest, src, weight)
else:
print('Edge already exists in the graph.')

elif choice == 'Shortest':
keyValue = int(do[1])
source = grh.getVertex(keyValue)
distance = dijkstraAlgorithm(grh, source)
print('Distances from {}: '.format(keyValue))
for v in distance:
print('Distance to {}: {}'.format(v.getKey(), distance[v]))
print()

elif choice == 'Show':
print('Vertices -> ', end='')
for v in grh:
print(v.getKey(), end=' ')
print()

print('Edges -> ')
for v in grh:
for dest in v.getNeighbours():
w = v.getWeight(dest)
print('(Source = {}, Destination = {}, Weight = {}) '.format(v.getKey(),
dest.getKey(), w))
print()

elif choice == 'EXIT':
break

Sample Output:

Undirected Graph
Menu
Add vertex <key>
Add edge <src> <dest> <weight>
Shortest <source vertex key>
Show
EXIT
Enter your choice: Add vertex 1
Enter your choice: Add vertex 2
Enter your choice: Add vertex 3
Enter your choice: Add edge 1 3 60
Enter your choice: Add edge 1 1 11
Enter your choice: Add edge 2 3 22
Enter your choice: Add edge 2 3 22
Edge already exists in the graph.
Enter your choice: Add edge 2 1 13
Enter your choice: Shortest 1
Distances from 1:
Distance to 1: 0
Distance to 2: 13
Distance to 3: 35

Enter your choice: EXIT


Related Solutions

Programming language is in python 3 For this project, you will import the json module. Write...
Programming language is in python 3 For this project, you will import the json module. Write a class named NobelData that reads a JSON file containing data on Nobel Prizes and allows the user to search that data. It just needs to read a local JSON file - it doesn't need to access the internet. Specifically, your class should have an init method that reads the file, and it should have a method named search_nobel that takes as parameters a...
Programming language is python 3 For this project, you will import the json module. Write a...
Programming language is python 3 For this project, you will import the json module. Write a class named NeighborhoodPets that has methods for adding a pet, deleting a pet, searching for the owner of a pet, saving data to a JSON file, loading data from a JSON file, and getting a set of all pet species. It will only be loading JSON files that it has previously created, so the internal organization of the data is up to you. The...
Please provide proper citation with page numbers of the material you are referencing in your homework...
Please provide proper citation with page numbers of the material you are referencing in your homework paper. Homework assignment should be 1-2 pages, not including reference page, double-spaced. Review an article related to a sentinel perioperative event. Be sure to summarize the article. Include the following: What is a sentinel event? Give background information on the patient (i.e. age, past medical history, admitting diagnosis). Discuss the cause of the sentinel event, if it resulted in any complications (i.e. injury, trauma,...
Using python programming language, compare the four tasks. 1. For the following exercises you will be...
Using python programming language, compare the four tasks. 1. For the following exercises you will be writing a program that implements Euler’s method (pronounced ‘oy-ler’). It may be the case that you have not yet encountered Euler’s method in the course. Euler’s method can be found in Chapter 10.2 of your notes, which gives a good description of why this algorithm works. But for our purposes, we only need to know the algorithm itself - so there’s no need to...
The programming language is Python Instructions: Create a function that will delete a node in a...
The programming language is Python Instructions: Create a function that will delete a node in a Linked List based on position number. On below example, if you want to delete position #2, it will remove the Banana (arrangement of nodes below is Apple, Banana, Cherry, Grapes, Orange). myLinkedList = LinkedList() myLinkedList.append("Banana") myLinkedList.append("Cherry") myLinkedList.append("Grapes") myLinkedList.append("Orange") myLinkedList.prepend("Apple") myLinkedList.deleteByPositionNum(2) node = myLinkedList.head while node: print(node.value, " ") node = node.next_node You may start with the function head: def deleteByPositionNum(self, positionNum):
Programming language Python It have to be in Functions with a main function Samuel is a...
Programming language Python It have to be in Functions with a main function Samuel is a math teacher at Hogwarts School of Witchcraft and Wizardry. He loves to give his students multiplication exercises. However, he doesn’t care about the actual operation result but the unit sum of its digits. At Hogwarts School of Witchcraft and Wizardry, they define the unit sum (US) of N as the unit that it is left after doing the sum of all the digits of...
Please solve using simple python programming language and make it easy to understand explain your code...
Please solve using simple python programming language and make it easy to understand explain your code as I am a beginner, use appropriate variable names which make the code easy to understand and edit if needed. A subsystem responsible for delivering priority numbers to an automated irrigation system has stopped working and you need to deliver a quick fix that will work until the actual subsystem is fixed by senior developer. As you are the newest addition to the development...
Please use markup language HTML5 please. For this homework assignment, you will create a Web site...
Please use markup language HTML5 please. For this homework assignment, you will create a Web site made up of three different pages and links between those pages Index.htm The Web pages in a site should have a similar look-and-feel. For this site, you should create a simple menu as follows: Create a horizontal line across the very top and bottom of the page. Also on the home (Index) page, create links to the other two pages. The links should appear...
Programming Language : Python Question a)Where and how do you get a program development environment for...
Programming Language : Python Question a)Where and how do you get a program development environment for this language? b) Are there any IDEs that support this language? If yes, where and how do you get it?
Can you please solve this using recursion/ dynamic programming? Any programming language is fine. Wallace the...
Can you please solve this using recursion/ dynamic programming? Any programming language is fine. Wallace the Weightlifting Walrus is training for a contest where it will have to lift 1000 kg. Wallace has some weight plates lying around, possibly of different weights, and its goal is to add some of the plates to a bar so that it can train with a weight as close as possible to 1000 kg. In case there exist two such numbers which are equally...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT