Skip to content

Commit 97a0c70

Browse files
committed
Create determinant_calculator.py
1 parent c9baa24 commit 97a0c70

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

matrix/determinant_calculator.py

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
# Wikipedia URL- https://en.wikipedia.org/wiki/Determinant
2+
3+
def get_minor(matrix: list[list[int] | list[float]], row: int, col: int) -> list[list[int] | list[float]]:
4+
"""
5+
Returns the minor matrix obtained by removing the specified row and column.
6+
7+
Parameters
8+
----------
9+
matrix : list[list[int] | list[float]]
10+
The original square matrix.
11+
row : int
12+
The row to remove.
13+
col : int
14+
The column to remove.
15+
16+
Returns
17+
-------
18+
list[list[int] | list[float]]
19+
Minor matrix.
20+
"""
21+
return [r[:col] + r[col+1:] for i, r in enumerate(matrix) if i != row]
22+
23+
24+
def determinant_manual(matrix: list[list[int] | list[float]]) -> int | float:
25+
"""
26+
Calculates the determinant of a square matrix using cofactor expansion.
27+
28+
Parameters
29+
----------
30+
matrix : list[list[int] | list[float]]
31+
A square matrix.
32+
33+
Returns
34+
-------
35+
int | float
36+
Determinant of the matrix.
37+
38+
Examples
39+
--------
40+
>>> determinant_manual([[1,2],[3,4]])
41+
-2
42+
>>> determinant_manual([[2]])
43+
2
44+
>>> determinant_manual([[1,2,3],[4,5,6],[7,8,9]])
45+
0
46+
"""
47+
n = len(matrix)
48+
49+
if n == 1:
50+
return matrix[0][0]
51+
52+
if n == 2:
53+
return matrix[0][0]*matrix[1][1] - matrix[0][1]*matrix[1][0]
54+
55+
det = 0
56+
for j in range(n):
57+
minor = get_minor(matrix, 0, j)
58+
cofactor = (-1) ** j * determinant_manual(minor)
59+
det += matrix[0][j] * cofactor
60+
return det
61+
62+
63+
if __name__ == "__main__":
64+
# Simple demo
65+
matrix_demo = [
66+
[1, 2, 3],
67+
[4, 5, 6],
68+
[7, 8, 9]
69+
]
70+
print(f"The determinant is: {determinant_manual(matrix_demo)}")

0 commit comments

Comments
 (0)