-
-
Save amankharwal/fefdd1c49e62321cf97b2bc7b7465e73 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SparseMatrix: | |
def __init__(self, numRows, numCols): | |
self._numRows = numRows | |
self._numCols = numCols | |
self._elementList = List() | |
def numRows(self): | |
return self._numRows | |
def numCols(self): | |
return self._numCols | |
def __setitem__(self, ndxTuple, scalar): | |
ndx = self.findPosition(ndxTuple[0],ndxTuple[1]) | |
if ndx is not None: | |
if scalar != 0.0: | |
self._elementList[ndx].value = scatter | |
else: | |
self._elementList[ndx].pop(ndx) | |
else: | |
if scalar != 0.0: | |
element = _MatrixElement(ndxTuple[0], ndxTuple[1], scalar) | |
self._elementList.append(element) | |
def scaleBy(self, scalar): | |
for element in self._elementList: | |
element.value *= scalar | |
def findPosition(self, row, col): | |
n = len(self._elementList) | |
for i in range(n): | |
if row == self._elementList[i].row and \ | |
col == self._elementList[i].col: | |
return i | |
return None | |
class _MatrixElement: | |
def __init__(self, row, col, value): | |
self.row = row | |
self.col = col | |
self.value = value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment