Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import copy
- from sys import stdin
- class MatrixError(BaseException):
- def __init__(self, matrix1, matrix2):
- self.matrix1 = matrix1
- self.matrix2 = matrix2
- class Matrix:
- def __init__(self, matrix):
- self.matrix = copy.deepcopy(matrix)
- def __str__(self):
- result = ''
- for i in range(len(self.matrix)):
- if i < len(self.matrix) - 1:
- for j in range(len(self.matrix[i])):
- if j < len(self.matrix[i]) - 1:
- result += str(self.matrix[i][j]) + '\t'
- else:
- result += str(self.matrix[i][j]) + '\n'
- else:
- for j in range(len(self.matrix[i])):
- if j < len(self.matrix[i]) - 1:
- result += str(self.matrix[i][j]) + '\t'
- else:
- result += str(self.matrix[i][j])
- return result
- def size(self):
- return len(self.matrix), len(self.matrix[1])
- def __add__(self, other):
- arrows = len(self.matrix) == len(other.matrix)
- columns = len(self.matrix[0]) == len(other.matrix[0])
- if arrows and columns:
- newMatrix = list()
- for i in range(len(self.matrix)):
- line = []
- for j in range(len(self.matrix[i])):
- line.append(self.matrix[i][j] + other.matrix[i][j])
- newMatrix.append(line)
- line = []
- return Matrix(newMatrix)
- else:
- raise MatrixError(self, other)
- def __mul__(self, other):
- if isinstance(other, float) or isinstance(other, int):
- newMatrix = list()
- for i in range(len(self.matrix)):
- line = []
- for j in range(len(self.matrix[i])):
- line.append(self.matrix[i][j] * other)
- newMatrix.append(line)
- line = []
- elif isinstance(other, Matrix):
- arrows = len(other.matrix)
- columns = len(self.matrix[0])
- if arrows == columns:
- pass
- return Matrix(newMatrix)
- __rmul__ = __mul__
- def transposed(self):
- newMatrix = []
- for j in range(len(self.matrix[0])):
- newMatrix.append([])
- for i in range(len(self.matrix)):
- newMatrix[j].append(self.matrix[i][j])
- return Matrix(newMatrix)
- def transpose(self):
- newMatrix = []
- for j in range(len(self.matrix[0])):
- newMatrix.append([])
- for i in range(len(self.matrix)):
- newMatrix[j].append(self.matrix[i][j])
- self.matrix = newMatrix
- return Matrix(newMatrix)
- exec(stdin.read())
Advertisement
Add Comment
Please, Sign In to add comment