From d65e89417754fce1839e6eae2b600fd5d27fb25c Mon Sep 17 00:00:00 2001 From: yznnck Date: Wed, 14 Sep 2022 14:00:55 +0200 Subject: [PATCH 1/3] Fix minor typo in comment --- matrix/inverse_of_matrix.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matrix/inverse_of_matrix.py b/matrix/inverse_of_matrix.py index 9deca6c3c08e..5c6fc2cd5fb3 100644 --- a/matrix/inverse_of_matrix.py +++ b/matrix/inverse_of_matrix.py @@ -27,7 +27,7 @@ def inverse_of_matrix(matrix: list[list[float]]) -> list[list[float]]: [[0.25, -0.5], [-0.3, 1.0]] """ - D = Decimal # An abbreviation to be conciseness + D = Decimal # An abbreviation for conciseness # Calculate the determinant of the matrix determinant = D(matrix[0][0]) * D(matrix[1][1]) - D(matrix[1][0]) * D(matrix[0][1]) if determinant == 0: From bc477e628c28a5e2556f22fe4ac5e30f811efcb5 Mon Sep 17 00:00:00 2001 From: yznnck Date: Wed, 14 Sep 2022 14:03:58 +0200 Subject: [PATCH 2/3] Add matrix dimension check --- matrix/inverse_of_matrix.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/matrix/inverse_of_matrix.py b/matrix/inverse_of_matrix.py index 5c6fc2cd5fb3..9a76dd43df14 100644 --- a/matrix/inverse_of_matrix.py +++ b/matrix/inverse_of_matrix.py @@ -28,13 +28,19 @@ def inverse_of_matrix(matrix: list[list[float]]) -> list[list[float]]: """ D = Decimal # An abbreviation for conciseness + + if len(matrix) != 2 or len(matrix[0]) != 2 or len(matrix[1]) != 2: + raise ValueError("Please provide a matrix of size 2x2.") + # Calculate the determinant of the matrix determinant = D(matrix[0][0]) * D(matrix[1][1]) - D(matrix[1][0]) * D(matrix[0][1]) if determinant == 0: raise ValueError("This matrix has no inverse.") + # Creates a copy of the matrix with swapped positions of the elements swapped_matrix = [[0.0, 0.0], [0.0, 0.0]] swapped_matrix[0][0], swapped_matrix[1][1] = matrix[1][1], matrix[0][0] swapped_matrix[1][0], swapped_matrix[0][1] = -matrix[1][0], -matrix[0][1] + # Calculate the inverse of the matrix return [[float(D(n) / determinant) or 0.0 for n in row] for row in swapped_matrix] From fd963de14f8c6165d9036484b4513d7aee6bab55 Mon Sep 17 00:00:00 2001 From: yznnck Date: Wed, 14 Sep 2022 14:06:36 +0200 Subject: [PATCH 3/3] Add descriptive comment --- matrix/inverse_of_matrix.py | 1 + 1 file changed, 1 insertion(+) diff --git a/matrix/inverse_of_matrix.py b/matrix/inverse_of_matrix.py index 9a76dd43df14..e414ee254c10 100644 --- a/matrix/inverse_of_matrix.py +++ b/matrix/inverse_of_matrix.py @@ -29,6 +29,7 @@ def inverse_of_matrix(matrix: list[list[float]]) -> list[list[float]]: D = Decimal # An abbreviation for conciseness + # Check if the provided matrix has 2 rows and 2 columns, since this implementation only works for 2x2 matrices if len(matrix) != 2 or len(matrix[0]) != 2 or len(matrix[1]) != 2: raise ValueError("Please provide a matrix of size 2x2.")