Skip to content

Commit 91c671e

Browse files
authored
Fix minor typo and add matrix dimension check (TheAlgorithms#6367)
* Fix minor typo in comment * Add matrix dimension check * Add descriptive comment
1 parent 5754bd0 commit 91c671e

File tree

1 file changed

+8
-1
lines changed

1 file changed

+8
-1
lines changed

matrix/inverse_of_matrix.py

+8-1
Original file line numberDiff line numberDiff line change
@@ -27,14 +27,21 @@ def inverse_of_matrix(matrix: list[list[float]]) -> list[list[float]]:
2727
[[0.25, -0.5], [-0.3, 1.0]]
2828
"""
2929

30-
D = Decimal # An abbreviation to be conciseness
30+
D = Decimal # An abbreviation for conciseness
31+
32+
# Check if the provided matrix has 2 rows and 2 columns, since this implementation only works for 2x2 matrices
33+
if len(matrix) != 2 or len(matrix[0]) != 2 or len(matrix[1]) != 2:
34+
raise ValueError("Please provide a matrix of size 2x2.")
35+
3136
# Calculate the determinant of the matrix
3237
determinant = D(matrix[0][0]) * D(matrix[1][1]) - D(matrix[1][0]) * D(matrix[0][1])
3338
if determinant == 0:
3439
raise ValueError("This matrix has no inverse.")
40+
3541
# Creates a copy of the matrix with swapped positions of the elements
3642
swapped_matrix = [[0.0, 0.0], [0.0, 0.0]]
3743
swapped_matrix[0][0], swapped_matrix[1][1] = matrix[1][1], matrix[0][0]
3844
swapped_matrix[1][0], swapped_matrix[0][1] = -matrix[1][0], -matrix[0][1]
45+
3946
# Calculate the inverse of the matrix
4047
return [[float(D(n) / determinant) or 0.0 for n in row] for row in swapped_matrix]

0 commit comments

Comments
 (0)