forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmatrix_class.py
366 lines (326 loc) · 11 KB
/
matrix_class.py
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
# An OOP approach to representing and manipulating matrices
from __future__ importannotations
classMatrix:
"""
Matrix object generated from a 2D array where each element is an array representing
a row.
Rows can contain type int or float.
Common operations and information available.
>>> rows = [
... [1, 2, 3],
... [4, 5, 6],
... [7, 8, 9]
... ]
>>> matrix = Matrix(rows)
>>> print(matrix)
[[1. 2. 3.]
[4. 5. 6.]
[7. 8. 9.]]
Matrix rows and columns are available as 2D arrays
>>> matrix.rows
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> matrix.columns()
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Order is returned as a tuple
>>> matrix.order
(3, 3)
Squareness and invertability are represented as bool
>>> matrix.is_square
True
>>> matrix.is_invertable()
False
Identity, Minors, Cofactors and Adjugate are returned as Matrices. Inverse can be
a Matrix or Nonetype
>>> print(matrix.identity())
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
>>> print(matrix.minors())
[[-3. -6. -3.]
[-6. -12. -6.]
[-3. -6. -3.]]
>>> print(matrix.cofactors())
[[-3. 6. -3.]
[6. -12. 6.]
[-3. 6. -3.]]
>>> # won't be apparent due to the nature of the cofactor matrix
>>> print(matrix.adjugate())
[[-3. 6. -3.]
[6. -12. 6.]
[-3. 6. -3.]]
>>> matrix.inverse()
Traceback (most recent call last):
...
TypeError: Only matrices with a non-zero determinant have an inverse
Determinant is an int, float, or Nonetype
>>> matrix.determinant()
0
Negation, scalar multiplication, addition, subtraction, multiplication and
exponentiation are available and all return a Matrix
>>> print(-matrix)
[[-1. -2. -3.]
[-4. -5. -6.]
[-7. -8. -9.]]
>>> matrix2 = matrix * 3
>>> print(matrix2)
[[3. 6. 9.]
[12. 15. 18.]
[21. 24. 27.]]
>>> print(matrix + matrix2)
[[4. 8. 12.]
[16. 20. 24.]
[28. 32. 36.]]
>>> print(matrix - matrix2)
[[-2. -4. -6.]
[-8. -10. -12.]
[-14. -16. -18.]]
>>> print(matrix ** 3)
[[468. 576. 684.]
[1062. 1305. 1548.]
[1656. 2034. 2412.]]
Matrices can also be modified
>>> matrix.add_row([10, 11, 12])
>>> print(matrix)
[[1. 2. 3.]
[4. 5. 6.]
[7. 8. 9.]
[10. 11. 12.]]
>>> matrix2.add_column([8, 16, 32])
>>> print(matrix2)
[[3. 6. 9. 8.]
[12. 15. 18. 16.]
[21. 24. 27. 32.]]
>>> print(matrix * matrix2)
[[90. 108. 126. 136.]
[198. 243. 288. 304.]
[306. 378. 450. 472.]
[414. 513. 612. 640.]]
"""
def__init__(self, rows: list[list[int]]):
error=TypeError(
"Matrices must be formed from a list of zero or more lists containing at "
"least one and the same number of values, each of which must be of type "
"int or float."
)
iflen(rows) !=0:
cols=len(rows[0])
ifcols==0:
raiseerror
forrowinrows:
iflen(row) !=cols:
raiseerror
forvalueinrow:
ifnotisinstance(value, (int, float)):
raiseerror
self.rows=rows
else:
self.rows= []
# MATRIX INFORMATION
defcolumns(self) ->list[list[int]]:
return [[row[i] forrowinself.rows] foriinrange(len(self.rows[0]))]
@property
defnum_rows(self) ->int:
returnlen(self.rows)
@property
defnum_columns(self) ->int:
returnlen(self.rows[0])
@property
deforder(self) ->tuple[int, int]:
returnself.num_rows, self.num_columns
@property
defis_square(self) ->bool:
returnself.order[0] ==self.order[1]
defidentity(self) ->Matrix:
values= [
[0ifcolumn_num!=row_numelse1forcolumn_numinrange(self.num_rows)]
forrow_numinrange(self.num_rows)
]
returnMatrix(values)
defdeterminant(self) ->int:
ifnotself.is_square:
return0
ifself.order== (0, 0):
return1
ifself.order== (1, 1):
returnint(self.rows[0][0])
ifself.order== (2, 2):
returnint(
(self.rows[0][0] *self.rows[1][1])
- (self.rows[0][1] *self.rows[1][0])
)
else:
returnsum(
self.rows[0][column] *self.cofactors().rows[0][column]
forcolumninrange(self.num_columns)
)
defis_invertable(self) ->bool:
returnbool(self.determinant())
defget_minor(self, row: int, column: int) ->int:
values= [
[
self.rows[other_row][other_column]
forother_columninrange(self.num_columns)
ifother_column!=column
]
forother_rowinrange(self.num_rows)
ifother_row!=row
]
returnMatrix(values).determinant()
defget_cofactor(self, row: int, column: int) ->int:
if (row+column) %2==0:
returnself.get_minor(row, column)
return-1*self.get_minor(row, column)
defminors(self) ->Matrix:
returnMatrix(
[
[self.get_minor(row, column) forcolumninrange(self.num_columns)]
forrowinrange(self.num_rows)
]
)
defcofactors(self) ->Matrix:
returnMatrix(
[
[
self.minors().rows[row][column]
if (row+column) %2==0
elseself.minors().rows[row][column] *-1
forcolumninrange(self.minors().num_columns)
]
forrowinrange(self.minors().num_rows)
]
)
defadjugate(self) ->Matrix:
values= [
[self.cofactors().rows[column][row] forcolumninrange(self.num_columns)]
forrowinrange(self.num_rows)
]
returnMatrix(values)
definverse(self) ->Matrix:
determinant=self.determinant()
ifnotdeterminant:
raiseTypeError("Only matrices with a non-zero determinant have an inverse")
returnself.adjugate() * (1/determinant)
def__repr__(self) ->str:
returnstr(self.rows)
def__str__(self) ->str:
ifself.num_rows==0:
return"[]"
ifself.num_rows==1:
return"[["+". ".join(str(self.rows[0])) +"]]"
return (
"["
+"\n ".join(
[
"["+". ".join([str(value) forvalueinrow]) +".]"
forrowinself.rows
]
)
+"]"
)
# MATRIX MANIPULATION
defadd_row(self, row: list[int], position: int|None=None) ->None:
type_error=TypeError("Row must be a list containing all ints and/or floats")
ifnotisinstance(row, list):
raisetype_error
forvalueinrow:
ifnotisinstance(value, (int, float)):
raisetype_error
iflen(row) !=self.num_columns:
raiseValueError(
"Row must be equal in length to the other rows in the matrix"
)
ifpositionisNone:
self.rows.append(row)
else:
self.rows=self.rows[0:position] + [row] +self.rows[position:]
defadd_column(self, column: list[int], position: int|None=None) ->None:
type_error=TypeError(
"Column must be a list containing all ints and/or floats"
)
ifnotisinstance(column, list):
raisetype_error
forvalueincolumn:
ifnotisinstance(value, (int, float)):
raisetype_error
iflen(column) !=self.num_rows:
raiseValueError(
"Column must be equal in length to the other columns in the matrix"
)
ifpositionisNone:
self.rows= [self.rows[i] + [column[i]] foriinrange(self.num_rows)]
else:
self.rows= [
self.rows[i][0:position] + [column[i]] +self.rows[i][position:]
foriinrange(self.num_rows)
]
# MATRIX OPERATIONS
def__eq__(self, other: object) ->bool:
ifnotisinstance(other, Matrix):
returnNotImplemented
returnself.rows==other.rows
def__ne__(self, other: object) ->bool:
returnnotself==other
def__neg__(self) ->Matrix:
returnself*-1
def__add__(self, other: Matrix) ->Matrix:
ifself.order!=other.order:
raiseValueError("Addition requires matrices of the same order")
returnMatrix(
[
[self.rows[i][j] +other.rows[i][j] forjinrange(self.num_columns)]
foriinrange(self.num_rows)
]
)
def__sub__(self, other: Matrix) ->Matrix:
ifself.order!=other.order:
raiseValueError("Subtraction requires matrices of the same order")
returnMatrix(
[
[self.rows[i][j] -other.rows[i][j] forjinrange(self.num_columns)]
foriinrange(self.num_rows)
]
)
def__mul__(self, other: Matrix|float) ->Matrix:
ifisinstance(other, (int, float)):
returnMatrix(
[[int(element*other) forelementinrow] forrowinself.rows]
)
elifisinstance(other, Matrix):
ifself.num_columns!=other.num_rows:
raiseValueError(
"The number of columns in the first matrix must "
"be equal to the number of rows in the second"
)
returnMatrix(
[
[Matrix.dot_product(row, column) forcolumninother.columns()]
forrowinself.rows
]
)
else:
raiseTypeError(
"A Matrix can only be multiplied by an int, float, or another matrix"
)
def__pow__(self, other: int) ->Matrix:
ifnotisinstance(other, int):
raiseTypeError("A Matrix can only be raised to the power of an int")
ifnotself.is_square:
raiseValueError("Only square matrices can be raised to a power")
ifother==0:
returnself.identity()
ifother<0:
ifself.is_invertable():
returnself.inverse() ** (-other)
raiseValueError(
"Only invertable matrices can be raised to a negative power"
)
result=self
for_inrange(other-1):
result*=self
returnresult
@classmethod
defdot_product(cls, row: list[int], column: list[int]) ->int:
returnsum(row[i] *column[i] foriinrange(len(row)))
if__name__=="__main__":
importdoctest
doctest.testmod()