左下三角矩陣壓縮(Python)

目錄

導語

解決方案

1. 以行爲主的存儲映射

2. 以列爲主的存儲映射

示例題目

1. 題目描述

2. 輸入/輸出 描述

3. 代碼

4. 代碼走讀

5. 測試用例

A. 正常使用場景

B. 輸入的數據不是整數

C. 輸入的矩陣行數不大於0

6. 傳送門


 

導語

下三角矩陣就是一種對角線以上元素都爲0的 n x n矩陣。其中左下三角矩陣是指對角線以上的元素都爲0。

由於下三角矩陣仍然有大量元素爲0,爲了避免浪費太多的內存空間,可以把三角矩陣的二維模式存儲在一維列表中。

 

a_{11} 0 0 0 0
a_{21} a_{22} 0 0 0
a_{31} a_{32} a_{33} 0 0
... ... ... ... 0
a_{n1} a_{n2} a_{n3} ... a_{nn}

對於如上所示的 n x n左下三角矩陣A(ij),如果i < j,那麼對應位置的元素值爲0。

 

解決方案

由於採用Python解決這個問題,一維列表不需要實現聲明大小。將該矩陣的有效元素映射爲一維列表存儲有兩種解決方案,映射方式分爲以行爲主和以列爲主兩種方式。

1. 以行爲主的存儲映射

以行爲主的存儲方案是先將左下三角矩陣的第一行對角線及對角線以下的元素存儲在一維列表中,然後在將左下三角矩陣的第二行對角線及對角線以下的元素存儲在一維列表中。。。以此類推存儲每一行元素。這樣存儲的一維列表中包含了左下三角矩陣中全部的有效元素。

a_{11} a_{21} a_{22} a_{31} a_{32} a_{33} ... a_{n1} a_{n2} a_{n3} ... a_{nn}

由上圖可知a_{ij}在一維數組中所對應的索引值k的對應關係爲:

k = n \cdot (j - 1) + i - \frac{j(j-1)}{2}

2. 以列爲主的存儲映射

同理,以列爲主的存儲如圖:

a_{11}
a_{21}
a_{31}
...
a_{n1}
...
a_{ij}
...
...
a_{nn}

由上圖可知a_{ij}在一維數組中所對應的索引值k的對應關係爲:

k = n \cdot (j - 1) + i - \frac{j(j-1)}{2}


無論選擇哪一種存儲映射,都可以將左下三角矩陣壓縮爲一個一維列表。本文選用以列爲主的存儲映射舉例說明

 

示例題目

1. 題目描述

設計一個Python程序,輸入一個左下三角矩陣,輸出壓縮後的一維數組。

 

2. 輸入/輸出 描述

輸入描述

輸入左下三角矩陣的總行數、默認數字,然後自動計算大小,提示輸入對應的數字。

Input matrix rows: 5
Input default value: 0
lower_triangular_matrix[0][0]: 34
lower_triangular_matrix[1][0]: 25
lower_triangular_matrix[1][1]: 39
lower_triangular_matrix[2][0]: 21
lower_triangular_matrix[2][1]: 23
lower_triangular_matrix[2][2]: 1
lower_triangular_matrix[3][0]: 98
lower_triangular_matrix[3][1]: 2
lower_triangular_matrix[3][2]: 56
lower_triangular_matrix[3][3]: 4
lower_triangular_matrix[4][0]: 59
lower_triangular_matrix[4][1]: 0
lower_triangular_matrix[4][2]: 2
lower_triangular_matrix[4][3]: 11
lower_triangular_matrix[4][4]: 3

輸出描述:

輸出原左下三角矩陣和壓縮成一維列表後的矩陣。

------lower triangular matrix------
|	34	0	0	0	0	|
|	25	39	0	0	0	|
|	21	23	1	0	0	|
|	98	2	56	4	0	|
|	59	0	2	11	3	|
------compress lower triangular matrix --> list ------
[34, 25, 39, 21, 23, 1, 98, 2, 56, 4, 59, 0, 2, 11, 3]

 

3. 代碼



class MatrixException(Exception):
    def __init__(self, message, code):
        self.message = message
        self.code = code


# 1. 輸入一個左下三角矩陣
try:
    rows = int(input("Input matrix rows: "))
    if rows <= 0:
        raise MatrixException("Matrix rows can not less than zero.", 1002)
    columns = rows
    default_value = int(input("Input default value: "))

    ltm = [[default_value] * columns for row in range(rows)]
    for row in range(rows):
        for column in range(columns):
            if column <= row:
                ltm[row][column] = int(input("lower_triangular_matrix[%d][%d]: "
                                             % (row, column)))
except ValueError as e:
    print("errcode: %s" % str(1001))
    print("errmsg: %s" % str(e))
    exit(1001)
except MatrixException as e:
    print("errcode: %s" % e.code)
    print("errmsg: %s" % e.message)
    exit(e.code)

# 2. 壓縮左下三角矩陣
try:
    array_size = ((1 + rows) * rows) // 2
    compress = [None] * array_size

    pos = 0
    for row in range(rows):
        for column in range(columns):
            if column <= row:
                compress[pos] = ltm[row][column]
                pos += 1

    if None in compress:
        print("compress: %s" % compress)
        raise MatrixException("Compress upper triangular matrix failed.", 1002)
except MatrixException as e:
    print("errcode: %s" % e.code)
    print("errmsg: %s" % e.message)
    exit(e.code)


# 3. 打印結果
print("------lower triangular matrix------")

for row in range(rows):
    message = "|\t"
    for column in range(columns):
        message += str(ltm[row][column]) + "\t"
    message += "|"
    print(message)

print("------compress lower triangular matrix --> list ------")
print(compress)

 

4. 代碼走讀

# 自定義異常
class MatrixException(Exception):
    def __init__(self, message, code):
        self.message = message
        self.code = code


# 1. 輸入一個左下三角矩陣
try:
    # 輸入左下三角矩陣的行數,列數等於行數
    rows = int(input("Input matrix rows: "))
    if rows <= 0:
        raise MatrixException("Matrix rows can not less than zero.", 1002)
    columns = rows
    # 輸入默認數字
    default_value = int(input("Input default value: "))

    # 初始化左下三角矩陣
    ltm = [[default_value] * columns for row in range(rows)]
    for row in range(rows):
        for column in range(columns):
            if column <= row:
                ltm[row][column] = int(input("lower_triangular_matrix[%d][%d]: "
                                             % (row, column)))
except ValueError as e:
    print("errcode: %s" % str(1001))
    print("errmsg: %s" % str(e))
    exit(1001)
except MatrixException as e:
    print("errcode: %s" % e.code)
    print("errmsg: %s" % e.message)
    exit(e.code)

# 2. 壓縮左下三角矩陣,使用以列爲主的存儲映射
try:
    array_size = ((1 + rows) * rows) // 2
    compress = [None] * array_size

    pos = 0
    for row in range(rows):
        for column in range(columns):
            if column <= row:
                compress[pos] = ltm[row][column]
                pos += 1

    if None in compress:
        print("compress: %s" % compress)
        raise MatrixException("Compress upper triangular matrix failed.", 1002)
except MatrixException as e:
    print("errcode: %s" % e.code)
    print("errmsg: %s" % e.message)
    exit(e.code)


# 3. 打印結果
print("------lower triangular matrix------")

for row in range(rows):
    message = "|\t"
    for column in range(columns):
        message += str(ltm[row][column]) + "\t"
    message += "|"
    print(message)

print("------compress lower triangular matrix --> list ------")
print(compress)

 

5. 測試用例

A. 正常使用場景

Input matrix rows: 6
Input default value: 0
lower_triangular_matrix[0][0]: 34
lower_triangular_matrix[1][0]: 12
lower_triangular_matrix[1][1]: 5
lower_triangular_matrix[2][0]: 9
lower_triangular_matrix[2][1]: -3
lower_triangular_matrix[2][2]: 23
lower_triangular_matrix[3][0]: 51
lower_triangular_matrix[3][1]: -24
lower_triangular_matrix[3][2]: 3
lower_triangular_matrix[3][3]: 1
lower_triangular_matrix[4][0]: 40
lower_triangular_matrix[4][1]: 22
lower_triangular_matrix[4][2]: 7
lower_triangular_matrix[4][3]: 92
lower_triangular_matrix[4][4]: 99
lower_triangular_matrix[5][0]: 76
lower_triangular_matrix[5][1]: 29
lower_triangular_matrix[5][2]: -26
lower_triangular_matrix[5][3]: -2
lower_triangular_matrix[5][4]: 3
lower_triangular_matrix[5][5]: 6
------lower triangular matrix------
|	34	0	0	0	0	0	|
|	12	5	0	0	0	0	|
|	9	-3	23	0	0	0	|
|	51	-24	3	1	0	0	|
|	40	22	7	92	99	0	|
|	76	29	-26	-2	3	6	|
------compress lower triangular matrix --> list ------
[34, 12, 5, 9, -3, 23, 51, -24, 3, 1, 40, 22, 7, 92, 99, 76, 29, -26, -2, 3, 6]

B. 輸入的數據不是整數

Input matrix rows: k
errcode: 1001
errmsg: invalid literal for int() with base 10: 'k'

C. 輸入的矩陣行數不大於0

Input matrix rows: 0
errcode: 1002
errmsg: Matrix rows can not less than zero.

 

6. 傳送門

input()函數

int()函數

range()函數

print()函數

exit()函數

ValueError異常

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章