Skip to content

Instantly share code, notes, and snippets.

@Legend-Mukund
Last active December 9, 2024 12:41
Show Gist options
  • Select an option

  • Save Legend-Mukund/bfda7b30cc7e6945d9b4dcdca1bf8375 to your computer and use it in GitHub Desktop.

Select an option

Save Legend-Mukund/bfda7b30cc7e6945d9b4dcdca1bf8375 to your computer and use it in GitHub Desktop.
Created by Telegram bot
from typing import List
class Matrix:
"""
A class to represent a square matrix and perform basic matrix operations like addition and subtraction.
Attributes:
matrix (List[list]): A list of lists where each inner list represents a row of the matrix.
order (int): The order (size) of the square matrix, i.e., the number of rows or columns.
"""
def __init__(self, matrix: List[list], order: int = 2):
if len(matrix) != order:
raise ValueError(f"The matrix should have {order} rows, but it has {len(matrix)} rows.")
for i, mat in enumerate(matrix):
if len(mat) != order:
raise ValueError(f"Row {i} in the matrix does not have the expected number of elements. Expected {order} elements, but got {len(mat)}.")
self.matrix = matrix
self.order = order
def __add__(self, other):
if isinstance(other, Matrix):
if self.order != other.order:
raise ValueError("Matrices have different orders and cannot be added.")
result = []
for i in range(self.order):
row = [self.matrix[i][j] + other.matrix[i][j] for j in range(self.order)]
result.append(row)
return Matrix(result, self.order)
raise ValueError("Operand is not a Matrix.")
def __sub__(self, other):
if isinstance(other, Matrix):
if self.order != other.order:
raise ValueError("Matrices have different orders and cannot be subtracted.")
result = []
for i in range(self.order):
row = [self.matrix[i][j] - other.matrix[i][j] for j in range(self.order)]
result.append(row)
return Matrix(result, self.order)
raise ValueError("Operand is not a Matrix.")
def __repr__(self) -> str:
return f'{self.matrix}'
mat1 = Matrix([[2,3], [4,5]])
mat2 = Matrix([[2,3], [8,9]])
print(mat1+mat2)
print(mat1-mat2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment