Skip to content

Commit cdeff43

Browse files
committed
Update determinant_calculator.py
1 parent 0410048 commit cdeff43

File tree

1 file changed

+25
-9
lines changed

1 file changed

+25
-9
lines changed

matrix/determinant_calculator.py

Lines changed: 25 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,11 @@
1-
def get_minor(matrix: list[list[int] | list[float]], row: int, col: int) -> list[list[int] | list[float]]:
1+
# Determinant calculator using cofactor expansion.
2+
# Calculates the determinant of a square matrix recursively.
3+
# Wikipedia URL - https://en.wikipedia.org/wiki/Determinant
4+
5+
6+
def get_minor(
7+
matrix: list[list[int] | list[float]], row: int, col: int
8+
) -> list[list[int] | list[float]]:
29
"""
310
Returns the minor matrix obtained by removing the specified row and column.
411
@@ -18,12 +25,12 @@ def get_minor(matrix: list[list[int] | list[float]], row: int, col: int) -> list
1825
1926
Examples
2027
--------
21-
>>> get_minor([[1,2],[3,4]], 0, 0)
28+
>>> get_minor([[1, 2], [3, 4]], 0, 0)
2229
[[4]]
23-
>>> get_minor([[1,2,3],[4,5,6],[7,8,9]], 1, 1)
30+
>>> get_minor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 1, 1)
2431
[[1, 3], [7, 9]]
2532
"""
26-
return [r[:col] + r[col+1:] for i, r in enumerate(matrix) if i != row]
33+
return [r[:col] + r[col + 1 :] for i, r in enumerate(matrix) if i != row]
2734

2835

2936
def determinant_manual(matrix: list[list[int] | list[float]]) -> int | float:
@@ -44,11 +51,20 @@ def determinant_manual(matrix: list[list[int] | list[float]]) -> int | float:
4451
--------
4552
>>> determinant_manual([[2]])
4653
2
47-
>>> determinant_manual([[1, 2], [3, 4]])
54+
>>> determinant_manual([[1, 2],
55+
... [3, 4]])
4856
-2
49-
>>> determinant_manual([[1,2,3],[4,5,6],[7,8,9]])
57+
>>> determinant_manual([
58+
... [1, 2, 3],
59+
... [4, 5, 6],
60+
... [7, 8, 9]
61+
... ])
5062
0
51-
>>> determinant_manual([[3,0,2],[2,0,-2],[0,1,1]])
63+
>>> determinant_manual([
64+
... [3, 0, 2],
65+
... [2, 0, -2],
66+
... [0, 1, 1]
67+
... ])
5268
10
5369
"""
5470
n = len(matrix)
@@ -57,7 +73,7 @@ def determinant_manual(matrix: list[list[int] | list[float]]) -> int | float:
5773
return matrix[0][0]
5874

5975
if n == 2:
60-
return matrix[0][0]*matrix[1][1] - matrix[0][1]*matrix[1][0]
76+
return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
6177

6278
det = 0
6379
for j in range(n):
@@ -68,7 +84,7 @@ def determinant_manual(matrix: list[list[int] | list[float]]) -> int | float:
6884

6985

7086
if __name__ == "__main__":
71-
# Simple demo
87+
7288
matrix_demo = [
7389
[1, 2, 3],
7490
[4, 5, 6],

0 commit comments

Comments
 (0)