Матричные операции, управляемые с помощью меню, в Python: сложение, отображение и многое другое

Вот пример реализации матричного класса в Python вместе с программой, управляемой меню, для выполнения различных матричных операций:

class Matrix:
    def __init__(self, rows, cols):
        self.rows = rows
        self.cols = cols
        self.matrix = [[0] * cols for _ in range(rows)]
    def set_element(self, row, col, value):
        self.matrix[row][col] = value
    def get_element(self, row, col):
        return self.matrix[row][col]
    def add(self, other):
        if self.rows != other.rows or self.cols != other.cols:
            print("Matrix dimensions do not match for addition.")
            return None
        result = Matrix(self.rows, self.cols)
        for i in range(self.rows):
            for j in range(self.cols):
                result.set_element(i, j, self.get_element(i, j) + other.get_element(i, j))
        return result
    def display(self):
        for row in self.matrix:
            print(row)

def get_matrix_dimensions():
    rows = int(input("Enter the number of rows: "))
    cols = int(input("Enter the number of columns: "))
    return rows, cols

def create_matrix():
    rows, cols = get_matrix_dimensions()
    matrix = Matrix(rows, cols)
    for i in range(rows):
        for j in range(cols):
            value = int(input(f"Enter the element at position ({i}, {j}): "))
            matrix.set_element(i, j, value)
    return matrix

def menu():
    print("Matrix Operations:")
    print("1. Add matrices")
    print("2. Display a matrix")
    print("3. Quit")

def main():
    matrices = []
    while True:
        menu()
        choice = int(input("Enter your choice: "))
        if choice == 1:
            if len(matrices) < 2:
                print("Please create at least two matrices.")
                continue
            matrix1 = matrices.pop()
            matrix2 = matrices.pop()
            result = matrix1.add(matrix2)
            if result:
                matrices.append(result)
                print("Matrices added successfully.")
        elif choice == 2:
            if len(matrices) == 0:
                print("No matrices available.")
            else:
                matrix = matrices[-1]
                print("Matrix:")
                matrix.display()
        elif choice == 3:
            print("Exiting program...")
            break
        else:
            print("Invalid choice. Please try again.")
        print()
        if choice != 2:
            matrix = create_matrix()
            matrices.append(matrix)

if __name__ == "__main__":
    main()

Эта программа позволяет создавать матрицы, складывать матрицы и отображать матрицы. Программа, управляемая меню, позволяет вам выбрать нужную операцию, введя соответствующий вариант.