已知稀疏矩阵A和B,编程实现基于三元组顺序表实现A+B的运算。

Python数据结构。
已知稀疏矩阵A和B,编程实现基于三元组顺序表实现A+B的运算。

详细代码实现和注释如下,望采纳

class SparseMatrix:
    def __init__(self, rows, cols, values):
        self.rows = rows
        self.cols = cols
        self.values = values

    def add(self, other):
        # 初始化三元组顺序表
        result_rows = []
        result_cols = []
        result_values = []

        i = j = 0
        while i < len(self.rows) and j < len(other.rows):
            if self.rows[i] == other.rows[j] and self.cols[i] == other.cols[j]:
                result_rows.append(self.rows[i])
                result_cols.append(self.cols[i])
                result_values.append(self.values[i] + other.values[j])
                i += 1
                j += 1
            elif self.rows[i] < other.rows[j] or (self.rows[i] == other.rows[j] and self.cols[i] < other.cols[j]):
                result_rows.append(self.rows[i])
                result_cols.append(self.cols[i])
                result_values.append(self.values[i])
                i += 1
            else:
                result_rows.append(other.rows[j])
                result_cols.append(other.cols[j])
                result_values.append(other.values[j])
                j += 1

        # 将剩余的三元组加入结果表中
        while i < len(self.rows):
            result_rows.append(self.rows[i])
            result_cols.append(self.cols[i])
            result_values.append(self.values[i])
            i += 1
        while j < len(other.rows):
            result_rows.append(other.rows[j])
            result_cols.append(other.cols[j])
            result_values.append(other.values[j])
            j += 1

        return SparseMatrix(result_rows, result_cols, result_values)

# 示例
A = SparseMatrix([1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4])
B = SparseMatrix([1, 2, 3, 4], [1, 2, 3, 4], [4, 3, 2, 1])
C = A.add(B)
print(C.rows)  # [1, 2, 3, 4]
print(C.cols)  # [1, 2, 3, 4]
print(C.values)  # [5, 5, 5, 5]