Answer the question
In order to leave comments, you need to log in
How to competently implement the Matrix class in Python?
I'm taking the course "Introduction to Python" on Coursera, there are assignments from the last week, where OOP is studied, which is incomprehensible and terrible for a beginner. Below I give the task and the code I compiled (from g * and sticks), which does not pass even the first test in the analyzer. I beg you to show an example of a working code or correct mine, maybe then it will become clear how to work with matrices
Pictures with a description of the task and examples of course tests below:
from sys import stdin
from copy import deepcopy
class Matrix:
def __init__(self, list_of_lists):
self.matrix = deepcopy(list_of_lists)
def __str__(self):
return '\n'.join('\t'.join(map(str, row))
for row in self.matrix)
def size(self):
sizepair = (len(self.matrix), len(self.matrix[0]))
return sizepair
def __getitem__(self, idx):
return self.matrix[idx]
def __add__(self, other):
other = Matrix(other)
result = []
numbers = []
for i in range(len(self.matrix)):
for j in range(len(self.matrix[0])):
summa = other[i][j] + self.matrix[i][j]
numbers.append(summa)
if len(numbers) == len(self.matrix):
result.append(numbers)
numbers = []
return Matrix(result)
def __mul__(self, other):
if isinstance(other, int) or isinstance(other, float):
result = [[other * x for x in y] for y in self.list2D]
return Matrix(result)
elif self.dim_C != other.dim_R:
return 'Нельзя перемножить матрицы таких размерностей'
else:
a = range(self.dim_C)
b = range(self.dim_R)
c = range(other.dim_C)
result = []
for i in b:
res = []
for j in c:
el, m = 0, 0
for k in a:
m = self.list2D[i][k] * other.list2D[k][j]
el += m
res.append(el)
result.append(res)
return Matrix(result)
def __rmul__(self, other):
return self.__mul__(other)
Answer the question
In order to leave comments, you need to log in
Maybe it will help someone else with the course.
The problem turned out to be banal: I forgot at the end of the code exec(stdin.read())
Everything else is correct 100/100
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question