Answer the question
In order to leave comments, you need to log in
Where do the two extra line breaks come from?
I decided to practice OOP.
class Matrix(object):
def __init__(self,x,y,content):
''' x - height,
y - width,
content - two-dimensional array
Example: matrix = Matrix(3,2,
[ [1,2],
[3,4],
[5,6] ])'''
if len(content) == x:self.height = x
else:raise ValueError("Different height")
for i in range(self.height):
if len(content[i]) != y:raise ValueError("Different width")
self.width = y
self.content = content
def __repr__(self):
out = ''
for i in range(self.height):
out += ' '.join(map(str,self.content[i]))
out += '\n'
return out
def mul_on_num(self, number):
''' return Matrix object'''
ctx =[[number * self.content[i][j] for j in range(self.width)] for i in range(self.height)]
return Matrix(self.height,self.width,ctx)
def __add__(self, matrix):
if matrix.width != self.width or matrix.height != self.height:
raise ValueError("Different sizes of the matrix")
ctx =[[matrix.content[i][j] + self.content[i][j] for j in range(self.width)] for i in range(self.height)]
return Matrix(self.height,self.width,ctx)
def __mul__(self,matrix):
if self.width == matrix.height:
n = self.width;mode = 0
elif matrix.width == self.height:
n = matrix.width;mode = 1
else:
raise ValueError("Different size")
if mode:
c = [[0 for i in range(self.width)] for j in range(matrix.height)]
for i in range(matrix.height):
for j in range(self.width):
for k in range(n):
c[i][j] += matrix.content[i][k]*self.content[k][j]
return Matrix(matrix.height, self.width, c)
else:
c = [ [0 for i in range(matrix.width)] for j in range(self.height)]
for i in range(self.height):
for j in range(matrix.width):
for k in range(n):
c[i][j] += self.content[i][k] * matrix.content[k][j]
return Matrix(self.height,matrix.width, c)
from main import Matrix
m = Matrix(2,2,[ [2,2],[2,2] ])
s = Matrix(2,2,[ [2,2],[2,2] ])
print('\n'*10)
k = s*m
print(k)
8 8
8 8
.
.
2 2
2 2
.
.
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question