Graphs in Python

n58h2r發表於2024-10-04

Programming Task 1: Graphs in Python [10% of your final mark]

Deadline: Sunday 6 October 2024, 23:59

This is your first programming task of this module is about graphs and implementing Dijkstra’salgorithm. You will submit a SINGLE PYTHON FILE (main.py) found in the Task1.zip file onMoodle. Your job is to modify the main.py file only. Importing any libraries that are not alreadymported in the main.py file is STRICTLY FORBIDDEN and will be considered as cheating.We operate a strict zero tolerance policy on cheating and plagiarism and late penalties apply.Any deviation from the format specified above will result in you receiving the mark of zero.

THE TASK

What Are Graphs?

A weighted graph is defined as 𝐺 = (𝑁, 𝐸, 𝜆) where 𝑁 is the set of nodes, 𝐸 ⊆ 𝑁 × 𝑁 is the set ofedges where () ∈ 𝐸. Finally, 𝜆:𝐸 → ℕ is the weighting functionthat specifies the length of each edge. Further, we have 𝜆(𝑛

For example, below we have the representation of a graph 𝐺 = (𝑁,𝐸, 𝜆) where:

  • 𝑁 = {0,1,2},
  • 𝐸 = {(0,1), (1,0), (1,2), (2,1)},
  • 𝜆(0,1) = 𝜆(1,0) = 3 and 𝜆(1,2) = 𝜆(2,1) = 4.

What is an adjacency matrix?

An adjacency matrix of a weightedgraph 𝐺 = (𝑁, 𝐸, 𝜆) is a |𝑁| by |𝑁| matrix 𝑚 such that 𝑚

For example, the graph above has the below adjacency matrix:

4Your Python Implementation Open the main.py file from Task1.zip. THIS IS THE ONLY FILE YOU SHOULD CHANGE ANF UPLOAD TO MOODLE. ONLY UPLOAD THIS FILE AND DO NOT ADD ANY NEW IMPORT STATEMENTS TO IT. In order to test your score, simply run the main.py file.

(1) In order to obtain the first five marks:

Using the inf imported from math, modify the __init__, addEdge, and getAdjacencyMatrixmethods so thatthe initialisation method creates a graph with noOfNodes nodes, assume theyare called [0, 1, …, noOfNodes-1] and no edges. The addEdge method adds an edgebetween x and y of length weight. For example, you would write the below code to create thegraph on the previous page.

  g = Graph(3)

  • g.addEdge(0,1,3)
  • g.addEdge(1,2,4)
  • And then the below code
  • g.getAdjacencyMatrix()
  • would result in
  • [[0, 3, inf], [3, 0, 4], [inf, 4, 0]]

(2) In order to obtain the second five marks:Modify the shortestRoute method so that it returns a dictionary with the key distancecorresponding to the value of the total distance of the shortest route between the nodes x andy and the key path corresponding to the nodes in that route in order. You may find it useful tosearch for Dijkstra’s algorithm. For example, the g.shortestRoute(2,0) call for the g above

would result in:{"distance":7, "path":[2,1,0]}

相關文章