-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeterminant.py
55 lines (43 loc) · 1.33 KB
/
determinant.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
from math import pow
from copy import deepcopy
import pytest
def subset_matrix(matrix, row, col):
ret_matrix = []
cp_m = deepcopy(matrix)
del cp_m[row]
for el in cp_m:
ret_matrix.append(el[:col]+el[col+1:])
return ret_matrix
def determinant(matrix):
#your code here
if not matrix:
return None
if len(matrix) == 1 and len(matrix[0]) == 1:
return matrix[0][0]
# if len(matrix) == 2 and len(matrix[0]) == 2:
# return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
sum = 0
for indx, el in enumerate(matrix[0]):
sub_m = subset_matrix(matrix, 0, indx)
sum += el * (int(pow(-1, indx))) * determinant(sub_m)
return sum
@pytest.mark.parametrize(
"m,r,c,expected",
[
([[2,5,3], [1,-2,-1], [1, 3, 4]], 0, 0, [[-2,-1], [3, 4]]),
([[1,2,3,4], [1,2,3,4], [1,2,3,4], [1,2, 3, 4]], 0, 0, [[2,3,4],[2,3,4],[2,3,4]]),
([[1,2,3,4], [1,2,3,4], [1,2,3,4], [1,2, 3, 4]], 1, 2, [[1,2,4],[1,2,4],[1,2,4]]),
]
)
def test_subset_matrix(m, r, c, expected):
assert subset_matrix(m, r, c) == expected
@pytest.mark.parametrize(
"m,expected",
[
([[1]], 1),
([[1, 3], [2, 5]], -1),
([[2, 5, 3], [1, -2, -1], [1, 3, 4]], -20)
]
)
def test_determinant(m, expected):
assert determinant(m) == expected