Skip to content

Instantly share code, notes, and snippets.

@amankharwal
Created December 29, 2020 12:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amankharwal/fefdd1c49e62321cf97b2bc7b7465e73 to your computer and use it in GitHub Desktop.
Save amankharwal/fefdd1c49e62321cf97b2bc7b7465e73 to your computer and use it in GitHub Desktop.
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