forked from UnitTestBot/UTBotJava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmatrix.py
More file actions
82 lines (68 loc) · 2.45 KB
/
matrix.py
File metadata and controls
82 lines (68 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
from __future__ import annotations
from itertools import product
from typing import List
class MatrixException(Exception):
def __init__(self, description):
self.description = description
class Matrix:
def __init__(self, elements: List[List[float]]):
assert all(len(elements[i-1]) == len(row) for i, row in enumerate(elements))
self.elements = elements
@property
def dim(self) -> tuple[int, int]:
return (
len(self.elements),
max(len(self.elements[i]) for i in range(len(self.elements)))
if len(self.elements) > 0 else 0
)
def __repr__(self):
return str(self.elements)
def __eq__(self, other):
if isinstance(other, Matrix):
return self.elements == other.elements
def __add__(self, other: Matrix):
if self.dim == other.dim:
return Matrix([
[
elem + other_elem for elem, other_elem in
zip(self.elements[i], other.elements[i])
]
for i in range(self.dim[0])
])
def __mul__(self, other):
if isinstance(other, (int, float, complex)):
return Matrix([
[
elem * other for elem in
self.elements[i]
]
for i in range(self.dim[0])
])
else:
raise MatrixException("Wrong Type")
def __matmul__(self, other: Matrix):
if isinstance(other, Matrix):
if self.dim[1] == other.dim[0]:
result = [[0 for _ in range(self.dim[0])] * other.dim[1]]
for i, j in product(range(self.dim[0]), range(other.dim[1])):
result[i][j] = sum(
self.elements[i][k] * other.elements[k][j]
for k in range(self.dim[1])
)
return Matrix(result)
else:
MatrixException("Wrong dimensions")
else:
raise MatrixException("Wrong Type")
def is_diagonal(self) -> bool:
if self.dim[0] != self.dim[1]:
raise MatrixException("Bad matrix")
for i, row in enumerate(self.elements):
for j, elem in enumerate(row):
if i != j and elem != 0:
return False
return True
if __name__ == '__main__':
a = Matrix([[1., 2.]])
b = Matrix([[3.], [4.]])
print(a @ b)