diff --git a/linear_algebra/README.md b/linear_algebra/README.md index f1b554e139de..169cd074d396 100644 --- a/linear_algebra/README.md +++ b/linear_algebra/README.md @@ -45,7 +45,8 @@ This module contains some useful classes and functions for dealing with linear a - changeComponent(x,y,value) : changes the specified component. - component(x,y) : returns the specified component. - width() : returns the width of the matrix - - height() : returns the height of the matrix + - height() : returns the height of the matrix + - determinate() : returns the determinate of the matrix if it is square - operator + : implements the matrix-addition. - operator - _ implements the matrix-subtraction diff --git a/linear_algebra/src/lib.py b/linear_algebra/src/lib.py index bf9e0d302a89..2f7a1775371f 100644 --- a/linear_algebra/src/lib.py +++ b/linear_algebra/src/lib.py @@ -277,6 +277,33 @@ def height(self): """ return self.__height + def determinate(self) -> float: + """ + returns the determinate of an nxn matrix using Laplace expansion + """ + if self.__height == self.__width and self.__width >= 2: + total = 0 + if self.__width > 2: + for x in range(0, self.__width): + for y in range(0, self.__height): + total += ( + self.__matrix[x][y] + * (-1) ** (x + y) + * Matrix( + self.__matrix[0:x] + self.__matrix[x + 1 :], + self.__width - 1, + self.__height - 1, + ).determinate() + ) + else: + return ( + self.__matrix[0][0] * self.__matrix[1][1] + - self.__matrix[0][1] * self.__matrix[1][0] + ) + return total + else: + raise Exception("matrix is not square") + def __mul__(self, other): """ implements the matrix-vector multiplication. diff --git a/linear_algebra/src/tests.py b/linear_algebra/src/tests.py index b63f2ae8c2db..4123a7c9e663 100644 --- a/linear_algebra/src/tests.py +++ b/linear_algebra/src/tests.py @@ -118,6 +118,13 @@ def test_str_matrix(self): A = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3) self.assertEqual("|1,2,3|\n|2,4,5|\n|6,7,8|\n", str(A)) + def test_determinate(self): + """ + test for determinate() + """ + A = Matrix([[1, 1, 4, 5], [3, 3, 3, 2], [5, 1, 9, 0], [9, 7, 7, 9]], 4, 4) + self.assertEqual(-376, A.determinate()) + def test__mul__matrix(self): A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3, 3) x = Vector([1, 2, 3]) @@ -149,6 +156,13 @@ def test_squareZeroMatrix(self): str(squareZeroMatrix(5)), ) - +def force_test() -> None: + """ + This will ensure that pytest runs the unit tests above. + To explore https://github.com/TheAlgorithms/Python/pull/1124 uncomment the line below. + >>> # unittest.main() + """ + pass + if __name__ == "__main__": unittest.main()