hi i'm new to python and i have to create a dictionary based sparse matrix. This is my code so far; but unfortunately my output are all zeros and i have no columns. I really need to get this error fixed since i need to add and multiply matrices. Is there anyone that could please help.
class GeneralSparse1:
def __init__(self, mtx={}, m=3, n=3):
self.matrix = {}
self.m = m
self.n = n
self.matrix.update(mtx)
def __getitem__(self, ij):
return self.matrix.get(ij,0)
def __setitem__(self, ij, val):
self.matrix[i,j] = val
def __str__(self):
s = "["
if self.m> 0:
for i in range(self.m):
s += str(self[i])
if i < self.m:
s += ", "
for j in range(self.n):
s += str(self[j])
s += "]"
return s
My output :
from GeneralSparse1 import *
>>> if __name__=="__main__":
x = GeneralSparse1({(2,1):1.0}, 2, 3)
y = GeneralSparse1({(2,1):1.0}, 2, 3)
print x
print y
[0, 0, 000]
[0, 0, 000]
If you would like to refer to this comment somewhere else in this project, copy and paste the following link:
hi i'm new to python and i have to create a dictionary based sparse matrix. This is my code so far; but unfortunately my output are all zeros and i have no columns. I really need to get this error fixed since i need to add and multiply matrices. Is there anyone that could please help.
class GeneralSparse1:
def __init__(self, mtx={}, m=3, n=3):
self.matrix = {}
self.m = m
self.n = n
self.matrix.update(mtx)
def __getitem__(self, ij):
return self.matrix.get(ij,0)
def __setitem__(self, ij, val):
self.matrix[i,j] = val
def __str__(self):
s = "["
if self.m> 0:
for i in range(self.m):
s += str(self[i])
if i < self.m:
s += ", "
for j in range(self.n):
s += str(self[j])
s += "]"
return s
My output :
from GeneralSparse1 import *
>>> if __name__=="__main__":
x = GeneralSparse1({(2,1):1.0}, 2, 3)
y = GeneralSparse1({(2,1):1.0}, 2, 3)
print x
print y
[0, 0, 000]
[0, 0, 000]