Python 类 实现矩阵加法、矩阵乘法

矩阵加法需要矩阵同型
矩阵乘法A·B需要满足A的列等于B的行
代码如下

class MatrixCalc:
    A = []
    B = []

    def __init__(self, shapeA, shapeB):
        self.shapeA = shapeA
        self.shapeB = shapeB

    def input_(self):
        print("Please input the Matrix A and the Matrix B below:")
        MatrixCalc.A = []
        MatrixCalc.B = []
        for i in range(self.shapeA[0]):
            MatrixCalc.A.append([int(e) for e in input().split()])
        print("")
        for i in range(self.shapeA[1]):
            MatrixCalc.B.append([int(e) for e in input().split()])

    def add(self):
        if self.shapeA[0] != self.shapeB[0] or self.shapeA[1] != self.shapeB[1]:
            print("Error!")
        else:
            MatrixCalc.input_(self)
            print("The result is:")
            for i in range(self.shapeA[0]):
                print([MatrixCalc.A[i][j] + MatrixCalc.B[i][j] for j in range(self.shapeA[1])])

    def multiply(self):
        if self.shapeA[1] != self.shapeB[0]:
            print("Error!")
        else:
            MatrixCalc.input_(self)
            print("The result is:")
            C = []
            for i in range(self.shapeA[0]):
                tmp = []
                for k in range(self.shapeB[1]):
                    sum = 0
                    for j in range(self.shapeA[1]):
                        sum += MatrixCalc.A[i][j] * MatrixCalc.B[j][k]
                    tmp.append(sum)
                C.append(tmp)
            for i in C:
                for j in i:
                    print(j, end=' ')
                print()


if __name__ == '__main__':
    shapeA = [int(i) for i in input("Please input the shape of Matrix A:").split()]
    shapeB = [int(i) for i in input("Please input the shape of Matrix B:").split()]
    cal_mode = input("How do you want to calculate it? Choose one:\n[1] '+'\n[2] '*'\n")
    M = MatrixCalc(shapeA, shapeB)
    if cal_mode is '+':
        M.add()
    else:
        M.multiply()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值