H
H
hell0_w0rId2018-11-28 17:48:23
Python
hell0_w0rId, 2018-11-28 17:48:23

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)

Maybe I'm doing something wrong, but why when calling such a script:
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)

It turns out this is the conclusion:
8 8
8 8
.
.

Instead of a dot \n
At the very end there are two \n
I also tried to use __str__, but when I called m = Matrix(2,2,[ [2,2],[2,2] ]) I printed a matrix
2 2
2 2
.
.

Is it possible to improve something here (in terms of architecture, code beauty)?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question