假设n*n的稀疏矩阵A采用三元组表示,设计一个程序实现以下功能
时间: 2024-05-08 13:16:54 浏览: 91
:1. 输入矩阵A的维度n和非零元素个数t;
2. 输入矩阵A的三元组表示;
3. 输出矩阵A的稀疏矩阵表示;
4. 输出矩阵A的转置矩阵的稀疏矩阵表示。
以下是Python实现的代码:
```python
class SparseMatrix:
def __init__(self, n, t, elements):
self.n = n
self.t = t
self.elements = elements
def to_sparse(self):
sparse = []
for i in range(self.n):
row = []
for j in range(self.n):
found = False
for k, e in enumerate(self.elements):
if e[0] == i and e[1] == j:
row.append(e[2])
found = True
break
if not found:
row.append(0)
sparse.append(row)
return sparse
def transpose(self):
transposed_elements = [(e[1], e[0], e[2]) for e in self.elements]
transposed_elements.sort()
return SparseMatrix(self.n, self.t, transposed_elements)
if __name__ == '__main__':
n = int(input("请输入矩阵A的维度n:"))
t = int(input("请输入矩阵A的非零元素个数t:"))
elements = []
print("请按照行优先顺序输入矩阵A的三元组表示:")
for i in range(t):
row, col, val = map(int, input().split())
elements.append((row, col, val))
A = SparseMatrix(n, t, elements)
print("矩阵A的稀疏矩阵表示为:")
sparse = A.to_sparse()
for row in sparse:
print(row)
print("矩阵A的转置矩阵的稀疏矩阵表示为:")
transposed = A.transpose()
sparse = transposed.to_sparse()
for row in sparse:
print(row)
```
运行结果:
```
请输入矩阵A的维度n:3
请输入矩阵A的非零元素个数t:4
请按照行优先顺序输入矩阵A的三元组表示:
0 1 2
1 0 -1
1 2 3
2 1 4
矩阵A的稀疏矩阵表示为:
[0, 2, 0]
[-1, 0, 3]
[0, 4, 0]
矩阵A的转置矩阵的稀疏矩阵表示为:
[0, -1, 0]
[2, 0, 4]
[0, 3, 0]
```
阅读全文