矩阵相乘(Python)

目录

题目描述

解决方案

代码

代码走读

传送门

测试用例

1. 正常场景

2. 当矩阵中的数值不是数字类型时

3. 输入的矩阵维数不是数字类型时


题目描述

依次输入矩阵A, B的维数,并输入两个矩阵的元素。打印两个矩阵相乘(即A * B)的结果。

输入描述

先输入矩阵A的维数和元素。元素位置根据维数动态生成。

Please input matrix A row number: 2
Please input matrix A column number: 3
Please input number for matrixA[0][0]: 3
Please input number for matrixA[0][1]: 5
Please input number for matrixA[0][2]: 1
Please input number for matrixA[1][0]: 7
Please input number for matrixA[1][1]: 2
Please input number for matrixA[1][2]: 6

再输入矩阵B的维数和元素。元素位置根据维数动态生成。

Please input matrix B row number: 3
Please input matrix B column number: 2
Please input number for matrixB[0][0]: 1
Please input number for matrixB[0][1]: 6
Please input number for matrixB[1][0]: 23
Please input number for matrixB[1][1]: 8
Please input number for matrixB[2][0]: 2
Please input number for matrixB[2][1]: 5

输出描述

输出矩阵A, B,并打印A * B的结果:

A:
|	3	5	1	|
|	7	2	6	|
B:
|	1	6	|
|	23	8	|
|	2	5	|
matrixA * matrixB = 
C:
|	120	63	|
|	65	88	|

解决方案

1、输入矩阵A,B的维数、并动态生成矩阵中的元素的位置,提示用户输入每一个位置上对应的元素。

2、根据矩阵运算规则计算A* B,得到最终结果。

3、打印结果。

代码

class Matrix(object):
    def __init__(self, row, column, name):
        self.__row = row
        self.__column = column
        self.name = name
        self.__base = [[0] * column for i in range(row)]

    @property
    def row(self):
        return self.__row

    @property
    def column(self):
        return self.__column

    def __repr__(self):
        print_message_list = [self.name + ":"]
        for i in range(self.row):
            line = "|\t"
            for j in range(self.column):
                line += str(self.__base[i][j]) + "\t"
            line += "|"
            print_message_list.append(line)
        return "\n".join(print_message_list)

    __str__ = __repr__

    def set(self, row, column, value):
        self.__base[row][column] = value

    def get(self, row, column):
        return self.__base[row][column]

    def input(self):
        for i in range(self.row):
            for j in range(self.column):
                self.__base[i][j] = int(input("Please input number for matrix%s[%d][%d]: " % (self.name, i, j)))
        return

    def __mul__(self, other_matrix):
        if not isinstance(other_matrix, Matrix):
            raise TypeError("cannot multiply Matrix and %s" % type(other_matrix).__name__)

        result = Matrix(self.row, other_matrix.column, "result of %s * %s" % (self.name, other_matrix.name))
        for i in range(result.row):
            for j in range(result.column):
                a = 0
                b = 0
                while (a < self.column) and (b < other_matrix.row):
                    result.set(i, j, result.get(i, j) + self.get(i, a) * other_matrix.get(b, j))
                    a += 1
                    b += 1
        return result


def create(matrix_name):
    row = int(input("Please input matrix %s row number: " % matrix_name))
    column = int(input("Please input matrix %s column number: " % matrix_name))
    if row <= 0 or column <= 0:
        raise ValueError("matrix %s row and column less than or equal to zero" % matrix_name)
    return Matrix(row, column, matrix_name)


def main():
    matrix_a = create("A")
    matrix_a.input()

    matrix_b = create("B")
    matrix_b.input()

    matrix_c = matrix_a * matrix_b
    matrix_c.name = "C"
    print(matrix_a)
    print(matrix_b)
    print("matrix%s * matrix%s = " % (matrix_a.name, matrix_b.name))
    print(matrix_c)


if __name__ == '__main__':
    main()

代码走读

# 实现一个矩阵类Matrix,包含了矩阵的相关操作。
class Matrix(object):
    # 初始化一个矩阵对象需要三个参数:矩阵的行数row,列数column,以及矩阵的名称name。
    def __init__(self, row, column, name):
        self.__row = row
        self.__column = column
        self.name = name

        # self.__base是一个二维列表,该字段实际着存储矩阵的内部元素。
        # 默认情况下它会被初始化为 row * column 的二维列表,每个子列表的元素都初始化为0。
        self.__base = [[0] * column for i in range(row)]

    @property
    def row(self):
        return self.__row

    @property
    def column(self):
        return self.__column

    # 重写__repr__,定制矩阵打印的结果。
    def __repr__(self):
        print_message_list = [self.name + ":"]
        for i in range(self.row):
            line = "|\t"
            for j in range(self.column):
                line += str(self.__base[i][j]) + "\t"
            line += "|"
            print_message_list.append(line)
        return "\n".join(print_message_list)

    # 让__str__与__repr__的返回结果相同。
    __str__ = __repr__

    # 给出指定的行数row,列数column和新的值value,设置矩阵的值
    def set(self, row, column, value):
        self.__base[row][column] = value

    # 给定指定的行数row,列出column来获取矩阵的值
    def get(self, row, column):
        return self.__base[row][column]

    # 通过输入的方式填充矩阵。
    def input(self):
        for i in range(self.row):
            for j in range(self.column):
                self.__base[i][j] = int(input("Please input number for matrix%s[%d][%d]: " % (self.name, i, j)))
        return

    # 通过重写__mul__方法,定义矩阵相乘。
    def __mul__(self, other_matrix):
        if not isinstance(other_matrix, Matrix):
            raise TypeError("cannot multiply Matrix and %s" % type(other_matrix).__name__)

        result = Matrix(self.row, other_matrix.column, "result of %s * %s" % (self.name, other_matrix.name))
        for i in range(result.row):
            for j in range(result.column):
                a = 0
                b = 0
                while (a < self.column) and (b < other_matrix.row):
                    result.set(i, j, result.get(i, j) + self.get(i, a) * other_matrix.get(b, j))
                    a += 1
                    b += 1
        return result


# 定义一个工厂函数,用来创建矩阵。
def create(matrix_name):
    row = int(input("Please input matrix %s row number: " % matrix_name))
    column = int(input("Please input matrix %s column number: " % matrix_name))
    if row <= 0 or column <= 0:
        raise ValueError("matrix %s row and column less than or equal to zero" % matrix_name)
    return Matrix(row, column, matrix_name)


# 主函数
def main():
    matrix_a = create("A")
    matrix_a.input()

    matrix_b = create("B")
    matrix_b.input()

    # 矩阵c是由矩阵a和b相乘得出
    matrix_c = matrix_a * matrix_b
    matrix_c.name = "C"
    print(matrix_a)
    print(matrix_b)
    print("matrix%s * matrix%s = " % (matrix_a.name, matrix_b.name))
    print(matrix_c)


if __name__ == '__main__':
    main()

传送门

1. input()函数

Python input函数:接收标准输入数据_TCatTime的博客-CSDN博客_python接收输入参数

2. int()函数

Python int函数_TCatTime的博客-CSDN博客_int函数python

3. ValueError异常

Python异常 ValueError_TCatTime的博客-CSDN博客_python valueerror

4. print()函数

Python print函数:将对象打印输出_TCatTime的博客-CSDN博客_python打印

5. range()函数

Python range函数_TCatTime的博客-CSDN博客_python range

6. len()函数

Python len函数_TCatTime的博客-CSDN博客_len函数

7. exit()函数

Python exit函数_TCatTime的博客-CSDN博客_python的exit函数

测试用例

1. 正常场景

矩阵A(3 X 4),矩阵B(3 X 2)


Please input matrix A rows number: 3
Please input matrix A columns number: 4
------------
Please input number for matrixA[0][0]: 5
Please input number for matrixA[0][1]: 67
Please input number for matrixA[0][2]: 23
Please input number for matrixA[0][3]: 12
Please input number for matrixA[1][0]: 34
Please input number for matrixA[1][1]: 17
Please input number for matrixA[1][2]: 9
Please input number for matrixA[1][3]: 0
Please input number for matrixA[2][0]: 34
Please input number for matrixA[2][1]: 22
Please input number for matrixA[2][2]: 1
Please input number for matrixA[2][3]: 31
------------
Please input matrix B rows number: 3
Please input matrix B columns number: 2
------------
Please input number for matrixB[0][0]: 46
Please input number for matrixB[0][1]: 2
Please input number for matrixB[1][0]: 43
Please input number for matrixB[1][1]: 1
Please input number for matrixB[2][0]: 0
Please input number for matrixB[2][1]: 56


MatrixA: 
|	5	67	23	12	|
|	34	17	9	0	|
|	34	22	1	31	|


MatrixB: 
|	46	2	|
|	43	1	|
|	0	56	|

MatrixA * MatrixB = MatrixC
MatrixC: 
|	3111	1365	|
|	2295	589	|
|	2510	146	|


2. 当矩阵中的数值不是数字类型时

Please input matrix A rows number: 3
Please input matrix A columns number: 4
------------
Please input number for matrixA[0][0]: 12
Please input number for matrixA[0][1]: 3r
[ERROR]Please input integer number for matrixA element

代码拦截提示错误正确。

3. 输入的矩阵维数不是数字类型时

Please input matrix A rows number: er
[ERROR]Please input integer number for rows and column.

代码拦截提示正确。

你可能感兴趣的:(#,Python常见题目,Python,Python)