Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Matrix:
- def __init__(self, values):
- self._values = values
- @property
- def values(self):
- return self._values
- @values.setter
- def values(self, values):
- if (len(set(map(len, values)))) not in (0, 1):
- raise ValueError(
- 'Rows are not the same length'
- )
- self._values = values
- def __str__(self):
- stroca = ''
- for j in self._values:
- for i in j:
- stroca = stroca + str(i) + ' '
- stroca = stroca + '\n'
- return stroca
- @property
- def dimensions(self):
- x = len(self._values)
- if x:
- y = len(self.values[0])
- return x, y
- return 0, 0
- def __getitem__(self, i):
- x, y = i
- return self._values[x][y]
- def __multipl__(self, obj):
- if not self.dimensions == 0:
- result = []
- a = 0
- b = 0
- for j in self._values:
- result.append([])
- for i in j:
- result[a].append(i * obj)
- b += 1
- a += 1
- b = 0
- return Matrix(result)
- def __mul__(self, obj):
- result = [[obj * j for j in i] for i in self._values]
- return Matrix(result)
- __rmul__ = __mul__
- def __substtraction__(self, obj):
- if not isinstance(obj, Matrix):
- raise ValueError(
- "Object %s is not type of Matrix" % obj
- )
- if not self.dimensions == obj.dimensions:
- raise ValueError(
- "Matrix %s is not the same dimensions" % obj
- )
- a = obj.__multipl__(-1)
- result = [
- list(map(sum, zip(*t))) for t in zip(self.values, a.values)]
- return result
- def __add__(self, obj):
- if not isinstance(obj, Matrix):
- raise ValueError(
- "Object %s is not type of Matrix" % obj
- )
- if not self.dimensions == obj.dimensions:
- raise ValueError(
- "Matrix %s is not the same dimensions" % obj
- )
- result = [
- list(map(sum, zip(*t))) for t in zip(self.values, obj.values)]
- return result
- m = Matrix([[1, 2, 3], [4, 5, 6]])
- n = Matrix([[1, 1, 1], [4, 5, 6]])
- print(m)
- print(n)
- f = -10
- print(m.__multipl__(f))
- print(m.__mul__(n))
- print(m.__substtraction__(n))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement