已知稀疏矩阵A和B,编程代码实现基于三元组顺序表实现A+B的运算
时间: 2024-02-15 11:05:11 浏览: 34
下面是基于三元组顺序表实现稀疏矩阵A+B的Python代码:
```python
class SparseMatrixTriple:
def __init__(self, m, n, num):
self.m = m
self.n = n
self.num = num
def add(self, matrix_b):
if self.m != matrix_b.m or self.n != matrix_b.n:
raise ValueError('The dimensions of the two matrices are different!')
i = j = 1
k = 0
triple_c = []
while i <= self.num and j <= matrix_b.num:
if self.data[i][0] < matrix_b.data[j][0] or (
self.data[i][0] == matrix_b.data[j][0] and self.data[i][1] < matrix_b.data[j][1]):
triple_c.append(self.data[i])
i += 1
k += 1
elif self.data[i][0] > matrix_b.data[j][0] or (
self.data[i][0] == matrix_b.data[j][0] and self.data[i][1] > matrix_b.data[j][1]):
triple_c.append(matrix_b.data[j])
j += 1
k += 1
else:
triple_c.append((self.data[i][0], self.data[i][1], self.data[i][2] + matrix_b.data[j][2]))
i += 1
j += 1
k += 1
while i <= self.num:
triple_c.append(self.data[i])
i += 1
k += 1
while j <= matrix_b.num:
triple_c.append(matrix_b.data[j])
j += 1
k += 1
return SparseMatrixTriple(self.m, self.n, k, triple_c)
if __name__ == '__main__':
# A矩阵
m_a = 3
n_a = 4
num_a = 4
triple_a = [(1, 2, 2), (2, 3, 3), (3, 1, 4), (3, 4, 5)]
matrix_a = SparseMatrixTriple(m_a, n_a, num_a, triple_a)
# B矩阵
m_b = 3
n_b = 4
num_b = 3
triple_b = [(1, 2, 3), (2, 1, 1), (3, 4, 2)]
matrix_b = SparseMatrixTriple(m_b, n_b, num_b, triple_b)
# A+B矩阵
matrix_c = matrix_a.add(matrix_b)
print(matrix_c.data)
```
其中,SparseMatrixTriple类表示稀疏矩阵的三元组顺序表,add方法实现了矩阵加法运算。在main函数中,我们分别定义了矩阵A和矩阵B,并通过add方法得到了矩阵A+B。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)