class SparseMatrix:
def __init__(self, matrix):
self.matrix = matrix
self.m, self.n = len(matrix), len(matrix[0])
self.i, self.j, self.v = {}, {}, {}
for i in range(self.m):
for j in range(self.n):
if matrix[i][j] != 0:
self.i[(i, j)] = i
self.j[(i, j)] = j
self.v[(i, j)] = matrix[i][j]
def transpose(self):
result = [[0] * self.m for _ in range(self.n)]
for (i, j), v in self.i.items():
result[j][i] = v
return SparseMatrix(result)
def multiply(self, other):
if len(other.matrix) != self.n:
raise ValueError("矩阵乘法的前提是左矩阵的列数等于右矩阵的行数")
result = [[0] * len(other.matrix[0]) for _ in range(self.m)]
for (i1, j1), v1 in self.v.items():
for (i2, j2), v2 in other.v.items():
result[self.i[(i1, j1)]][i2] += v1 * v2
return SparseMatrix(result)
def print(self):
for i in range(self.m):
for j in range(self.n):
if (i, j) in self.i:
print(f"{self.v[(i, j)]}", end="")
else:
print(f"0 ", end="")
print()
if __name__ == "__main__":
a1=[[0,0,0],[1,1,1],[0,0,0]]
b1=[[1,1,0],[0,0,1],[1,1,1]]
a=SparseMatrix(a1)
a.transpose()
b=SparseMatrix(b1)
c=a.multiply(b)
c.print()