2017年10月4日 星期三

[Python練習] 3x3 矩陣運算 (加法、減法、乘法),不使用 Numpy


inputA = []
inputB = []

try:
    # Conver input "number" string to list
    inputA = list(map(int, input("Input a 3x3 matrix(A): ").split()))
    inputB = list(map(int, input("Input a 3x3 matrix(B): ").split()))
except ValueError:
    print("Error type 1: please input a number matrix")
except:
    print("Error type 2: unknow error")
else:
    # Check if the input matrix fit the criteria of 3x3 matrix
    if len(inputA) != len(inputB) and len(inputA) != 9:
        print('please input 3x3 matrix')
    else:
        matrixA = []
        matrixB = []
        matrixPlus = []
        matrixSub = []
        matrixMulti = []
        matrixDiv = []

        # Convert 1-way list to 2-way list (3x3 matrix)
        for x in range(0,len(inputA),3):
            matrixA.append(inputA[x:x+3])
            matrixB.append(inputB[x:x+3])
            #print(matrixA)

        # Calculate plus and sub
        for x in range(len(matrixA)):
            tmpPlus = []
            tmpSub = []
            for y in range(3):
                tmpPlus.append(matrixA[x][y] + matrixB[x][y])
                tmpSub.append(matrixA[x][y] - matrixB[x][y])
            matrixPlus.append(tmpPlus)
            matrixSub.append(tmpSub)

        # Calcuste multiple
        for k in range(len(matrixA)):
            tmpMulti = []
            for i in range(len(matrixB[0])):
                sum = 0
                for j in range(len(matrixB)):
                    sum += matrixA[k][j] * matrixB[j][i]
                tmpMulti.append(sum)
            matrixMulti.append(tmpMulti)

        print("MatrixA + MatrixB: " + str(matrixPlus))
        print("MatrixA - MatrixB: " + str(matrixSub))
        print("MatrixA * MatrixB: " + str(matrixMulti))

====================================================
執行結果:
Input a 3x3 matrix(A): 8 1 6 3 5 7 4 9 2
Input a 3x3 matrix(B): 1 2 3 4 5 6 7 8 9
MatrixA + MatrixB: [[9, 3, 9], [7, 10, 13], [11, 17, 11]]
MatrixA - MatrixB: [[7, -1, 3], [-1, 0, 1], [-3, 1, -7]]
MatrixA * MatrixB: [[54, 69, 84], [72, 87, 102], [54, 69, 84]]

沒有留言:

張貼留言