Update matrix_class.py (#1175)

This commit is contained in:
Christian Clauss 2019-09-10 07:49:07 +02:00 committed by GitHub
parent 3c3f92db53
commit 030600f9b3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -102,15 +102,15 @@ class Matrix:
def __init__(self, rows):
error = TypeError(
"Matrices must be formed from a list of zero or more lists containing at least one and the same number of values, \
each of which must be of type int or float"
"Matrices must be formed from a list of zero or more lists containing at least "
"one and the same number of values, each of which must be of type int or float."
)
if len(rows) != 0:
cols = len(rows[0])
if cols == 0:
raise error
for row in rows:
if not len(row) == cols:
if len(row) != cols:
raise error
for value in row:
if not isinstance(value, (int, float)):
@ -137,9 +137,7 @@ class Matrix:
@property
def is_square(self):
if self.order[0] == self.order[1]:
return True
return False
return self.order[0] == self.order[1]
def identity(self):
values = [
@ -168,9 +166,7 @@ class Matrix:
)
def is_invertable(self):
if self.determinant():
return True
return False
return bool(self.determinant())
def get_minor(self, row, column):
values = [
@ -218,9 +214,8 @@ class Matrix:
return Matrix(values)
def inverse(self):
if not self.is_invertable():
return None
return self.adjugate() * (1 / self.determinant())
determinant = self.determinant()
return None if not determinant else self.adjugate() * (1 / determinant)
def __repr__(self):
return str(self.rows)
@ -283,14 +278,10 @@ class Matrix:
def __eq__(self, other):
if not isinstance(other, Matrix):
raise TypeError("A Matrix can only be compared with another Matrix")
if self.rows == other.rows:
return True
return False
return self.rows == other.rows
def __ne__(self, other):
if self == other:
return False
return True
return not self == other
def __neg__(self):
return self * -1
@ -316,23 +307,20 @@ class Matrix:
)
def __mul__(self, other):
if not isinstance(other, (int, float, Matrix)):
raise TypeError(
"A Matrix can only be multiplied by an int, float, or another matrix"
)
if type(other) in (int, float):
if isinstance(other, (int, float)):
return Matrix([[element * other for element in row] for row in self.rows])
if type(other) is Matrix:
elif isinstance(other, Matrix):
if self.num_columns != other.num_rows:
raise ValueError(
"The number of columns in the first matrix must be equal to the number of rows in the second"
)
raise ValueError("The number of columns in the first matrix must "
"be equal to the number of rows in the second")
return Matrix(
[
[Matrix.dot_product(row, column) for column in other.columns()]
for row in self.rows
]
)
else:
raise TypeError("A Matrix can only be multiplied by an int, float, or another matrix")
def __pow__(self, other):
if not isinstance(other, int):
@ -360,5 +348,4 @@ class Matrix:
if __name__ == "__main__":
import doctest
test = doctest.testmod()
print(test)
doctest.testmod()