Programming Assignment 1 - Graphs and Adjacency Matrices
Due: Sep 6th at 5pm.
In this assignment you will program a graph class and a method for determining the number of paths of length at most k between two nodes. The key fact that you need to know in order to solve this problem is that element (i, j) of the kth power of the adjacency matrix is the number of paths of length exactly k between node i and node j. Now what is the kth power of a matrix? If A is your adjacency matrix, then its kth power is the product of A with itself k times, where product is matrix product.
Your code should be structured as a single python file called HW1.py. We will call to test your code as:
import HW1
g = HW1.load_dot(file_name)
num_paths = g.num_paths(node1, node2, k)
where node1 and node2 are the IDs of the two nodes, and
The graph is loaded from a file in dot format. An example graph is provided here, and the provided function should work for the limited subset of dot markup that we will use.
Here's some code to get you started:
class graph (object) :
def __init__(self, n) :
"""constructor for the graph class.
takes a single parameter which is the number of nodes
in the graph
"""
# set the number of nodes
self.n = n
# the number of edges
self.m = 0
# the adjacency matrix
self.matrix = [ [0 for i in range(n)] for i in range(n) ]
# a dictionary that maps node ids to their indices
self.node_id_map = {}
def __len__(self) :
return self.n
def num_paths(self, node1, node2, k) :
"""
returns the number of paths of length AT MOST k
between node1 and node2
node1 and node2 are the names of the two nodes as they
appear in the input file that contains the graph
"""
pass
def load_dot(file_name) :
file_handle = open(file_name, 'U')
file_handle.readline()
n = 0 # the number of nodes
# first you need to process the dot file to determine
# the number of nodes in the graph
g = graph(n)
file_handle.seek(0)
# go back to the beginning of the file
file_handle.readline()
for line in file_handle :
pass
# process each edge
return g
if __name__ == '__main__' :
g = load_dot('test.dot')
print g.num_paths('a', 'b', 2)
