# File: TestSparseMatrix.py # Description: Sparse matrix representation has a single linked # list having the row, column, and non-zero data in each link # Student Name: # Student UT EID: # Partner Name: # Partner UT EID: # Course Name: CS 313E # Unique Number: 53580 # Date Created: # Date Last Modified: class Link (object): def __init__ (self, row = 0, col = 0, data = 0, next = None): self.row = row self.col = col self.data = data self.next = next # returns a String representation of a Link (row, col, data) def __str__ (self): s = '' return s class LinkedList (object): def __init__ (self): self.first = None def insertLast (self, row, col, data): newLink = Link (row, col, data) current = self.first if (current == None): self.first = newLink return while (current.next != None): current = current.next current.next = newLink # returns a String representation of a LinkedList def __str__ (self): s = '' return s class Matrix (object): def __init__ (self, row = 0, col = 0): self.row = row self.col = col self.matrix = LinkedList() # Performs assignment operation: matrix[row][col] = data def setElement (self, row, col, data): return # Adds two sparse matrices def __add__ (self, other): return # Multiplies two sparse matrices def __mul__ (self, other): return # Returns a linked list representing a row def getRow (self, n): return # Returns a linked list representing a column def getCol (self, n): return # Returns a string representation of a matrix def __str__ (self): s = '' return s def readMatrix (inFile): line = inFile.readline().rstrip("\n").split() row = int (line[0]) col = int (line[1]) mat = Matrix (row, col) for i in range (row): line = inFile.readline().rstrip("\n").split() for j in range (col): elt = int(line[j]) if (elt != 0): mat.matrix.insertLast (i, j, elt) line = inFile.readline() return mat def main (): inFile = open ("matrix.txt", "r") print ("Test Matrix Addition") matA = readMatrix (inFile) print (matA) matB = readMatrix (inFile) print (matB) matC = matA + matB print (matC) print ("\nTest Matrix Multiplication") matP = readMatrix (inFile) print (matP) matQ = readMatrix (inFile) print (matQ) matR = matP * matQ print (matR) print ("\nTest Setting a Zero Element to a Non-Zero Value") matA.setElement (1, 1, 5) print (matA) print ("\nTest Getting a Row") row = matP.getRow(1) print (row) print ("\nTest Getting a Column") col = matQ.getCol(0) print (col) inFile.close() main()