-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmatrix.py
More file actions
89 lines (72 loc) · 2.7 KB
/
Copy pathmatrix.py
File metadata and controls
89 lines (72 loc) · 2.7 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
83
84
85
86
87
88
89
class Matrix:
def __init__(self, data):
self.data = data
self.rows = len(data)
self.cols = len(data[0])
if not all(len(row) == self.cols for row in data):
raise ValueError("Inconsistent row lengths")
def __str__(self):
return '\n'.join(' '.join(str(cell) for cell in row) for row in self.data)
def __repr__(self):
return f'Matrix\n({self})'
def __getitem__(self, idx):
return self.data[idx]
def __setitem__(self, idx, new_row):
self.data[idx] = new_row
def __add__(self,other):
if self.rows != other.rows or self.cols != other.cols:
raise ValueError("Matrices must have the same dimensions")
return Matrix([[self.data[i][j] + other.data[i][j] for j in range(self.cols)] for i in range(self.rows)])
def __sub__(self,other):
if self.rows != other.rows or self.cols != other.cols:
raise ValueError("Matrices must have the same dimensions")
return Matrix([[self.data[i][j] - other.data[i][j] for j in range(self.cols)] for i in range(self.rows)])
def __mul__(self,other):
if self.cols != other.rows:
raise ValueError("Number of columns in the first matrix must be equal to the number of rows in the second matrix")
return Matrix([[sum(self.data[i][k]*other.data[k][j] for k in range(self.cols)) for j in range(other.cols)] for i in range(self.rows)])
def __eq__(self,other):
if self.rows != other.rows or self.cols != other.cols:
return False
return all(self.data[i][j] == other.data[i][j] for j in range(self.cols) for i in range(self.rows))
def __len__(self):
return self.rows
def transpose(self):
return Matrix([[self.data[j][i] for j in range(self.rows)] for i in range(self.cols)])
def row(self, idx):
return self.data[idx]
def col(self, idx):
return [row[idx] for row in self.data]
def random(self,max_val = 100):
from random import randint
for i in range(self.rows):
for j in range(self.cols):
self.data[i][j] = randint(-max_val,max_val)
from Chapter2.gaussj import gaussj
if __name__ == "__main__":
m1 = Matrix([
[2, 1, -1],
[-3, -1, 2],
[-2, 1, 2]
])
m2 = Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]
])
# gaussj(m1, m2)
# print( m1 )
# print( m2 )
# m1.random()
# m2.random()
# gaussj(m1, m2)
# print( m1 )
# print( m2 )
m3 = Matrix([
['a', 2, 3],
[4, 5, 6],
[7, 8, 9]
])
print(m3)
m3.random()
print(m3)