python---数据结构---稀疏矩阵三元组存储

发布时间:2024年01月19日
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()

文章来源:https://blog.csdn.net/2202_75787160/article/details/135704449
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。