目录
稀疏矩阵的压缩
要想了解稀疏矩阵如何解压,就要首先知道如何压缩稀疏矩阵。
题目描述
对一个压缩后的稀疏矩阵进行解压缩,还原稀疏矩阵压缩前的状态。
输入描述:
# 稀疏矩阵的有效元素数
Total number of input elements: 8
# 稀疏元素
Input param sparse_element: 0
# 原矩阵行数
Matrix rows: 6
# 原矩阵列数
Matrix columns: 6
# 稀疏矩阵第1行开始一次录入所有元素
sparse_matrix[1][0]: 0
sparse_matrix[1][1]: 0
sparse_matrix[1][2]: 25
sparse_matrix[2][0]: 0
sparse_matrix[2][1]: 3
sparse_matrix[2][2]: 32
sparse_matrix[3][0]: 0
sparse_matrix[3][1]: 5
sparse_matrix[3][2]: -25
sparse_matrix[4][0]: 1
sparse_matrix[4][1]: 1
sparse_matrix[4][2]: 33
sparse_matrix[5][0]: 1
sparse_matrix[5][1]: 2
sparse_matrix[5][2]: 77
sparse_matrix[6][0]: 2
sparse_matrix[6][1]: 3
sparse_matrix[6][2]: 55
sparse_matrix[7][0]: 4
sparse_matrix[7][1]: 0
sparse_matrix[7][2]: 101
sparse_matrix[8][0]: 5
sparse_matrix[8][1]: 2
sparse_matrix[8][2]: 38
输出描述
输出压缩矩阵和解压后的原矩阵:
------sparse_matrix------
| 6 6 8 |
| 0 0 25 |
| 1 3 32 |
| 0 5 -25 |
| 1 1 33 |
| 1 2 77 |
| 2 3 55 |
| 4 0 101 |
| 5 2 38 |
---------------
Decompression matrix: sparse_matrix ---> matrix
------matrix------
| 25 0 0 0 0 -25 |
| 0 33 77 32 0 0 |
| 0 0 0 55 0 0 |
| 0 0 0 0 0 0 |
| 101 0 0 0 0 0 |
| 0 0 38 0 0 0 |
解决方案
根据压缩矩阵的压缩方式,从压缩矩阵中读取原矩阵的配置方式,包括行数、列数和非稀疏元素数量,并根据配置初始化原矩阵。
在读取各个非稀疏元素的位置及值。根据位置将元素依次填充到原矩阵中完成解压。
代码
class MatrixException(Exception):
def __init__(self, message, code):
self.message = message
self.code = code
def print_matrix(matrix):
"""
Print matrix.
:param matrix: matrix
:return: None
"""
for row in range(len(matrix)):
message = "|\t"
for column in range(len(matrix[row])):
message += str(matrix[row][column]) + "\t"
message += "|"
print(message)
return
# 1. 读入稀疏矩阵,并做校验
try:
elements_amount = int(input("Total number of input elements: "))
if elements_amount < 0:
raise MatrixException("Total number of input elements must more than zero."
, 1002)
sparse_element = int(input("Input param sparse_element: "))
sparse_matrix = [[sparse_element] * 3 for row in range(elements_amount + 1)]
sparse_matrix[0][0] = int(input("Matrix rows: "))
if sparse_matrix[0][0] <= 0:
rai