初等變換(elementary transformation)是三種基本的變換,即交換(switching),相乘(multiplication)和相加(addition),
以下是關于實作初等變換的Python3代碼,不需要用numpy和matlib等第三方模塊,可能這不是最好,最簡單的,但能實作功能,拋磚引玉,
其中程式已定義了一個二維串列變數matrix,并滿足矩陣的條件,如matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
交換:
1 switch_num = input("請輸入需要交換的那兩行的編號:").split() 2 a, b = int(switch_num[0])-1, int(switch_num[1])-1 3 for num in range(len(matrix[0])): 4 matrix[a][num], matrix[b][num] = matrix[b][num], matrix[a][num]
相乘:
1 command = input("按格式:[行編號] [*或/] [乘數或除數]來輸入:").split() 2 row_num, sign, k = int(command[0])-1, command[1], float(command[2]) 3 if k == 0: 4 raise MathError("Can't be multiplied by a zero constants.") 5 else: 6 for num in range(len(matrix[0])): 7 if sign == "*": 8 matrix[row_num][num] *= k 9 elif sign == "/": 10 matrix[row_num][num] /= k
說明一下,第4行我自定義了一個錯誤,因為規定,做相乘運算時,乘數不可為0,自然除數也不能為0,所以要引發錯誤來提醒用戶,
自定義的錯誤:
1 class MathError(Exception): 2 def __init__(self, value): 3 self.value =https://www.cnblogs.com/toshihiko/p/ value 4 5 def __str__(self): 6 return self.value
相加:
1 command = input("按格式:[行編號] [+或-] [系數] [另一個行編號]來輸入:").split() 2 row_num_a, sign, k, row_num_b = int(command[0])-1, command[1], float(command[2]), int(command[3])-1 3 if row_num_a == row_num_b: 4 raise MathError("Can't operate in the same row/column.") 5 else: 6 for num, item in enumerate(matrix[row_num_b]): 7 if sign == "+": 8 matrix[row_num_a][num] += k * item 9 elif cmd[2] == "-": 10 matrix[row_num_a][num] -= k * item
說明,規定不能對同一行進行加減,若用戶輸入的兩個行編號相同,則引發自定義錯誤
以上這些代碼都是關于行(row)操作的,那要怎樣進行列(column)操作捏?
那就先轉置(transpose)一次矩陣,然后對這個轉置矩陣進行行操作,再轉置回來,即 轉置→行操作→轉置,
轉置:
1 matrix = [list(temp) for temp in zip(*matrix)]
就醬= ̄ω ̄=
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/158288.html
標籤:Python
上一篇:密碼類
下一篇:階乘類
