Update matrix_operation.py (#2344)

* Update matrix_operation.py

* Update matrix_operation.py

* Update matrix_operation.py

* Update matrix_operation.py

* Update matrix_operation.py

* Update matrix_operation.py
This commit is contained in:
wuyudi 2020-08-22 02:41:48 +08:00 committed by GitHub
parent ae33419c12
commit 6822d1afeb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -15,9 +15,8 @@ def add(*matrix_s: List[list]) -> List[list]:
[[7, 14], [12, 16]] [[7, 14], [12, 16]]
""" """
if all(_check_not_integer(m) for m in matrix_s): if all(_check_not_integer(m) for m in matrix_s):
a, *b = matrix_s for i in matrix_s[1:]:
for matrix in b: _verify_matrix_sizes(matrix_s[0], i)
_verify_matrix_sizes(a, matrix)
return [[sum(t) for t in zip(*m)] for m in zip(*matrix_s)] return [[sum(t) for t in zip(*m)] for m in zip(*matrix_s)]
@ -28,8 +27,9 @@ def subtract(matrix_a: List[list], matrix_b: List[list]) -> List[list]:
>>> subtract([[1,2.5],[3,4]],[[2,3],[4,5.5]]) >>> subtract([[1,2.5],[3,4]],[[2,3],[4,5.5]])
[[-1, -0.5], [-1, -1.5]] [[-1, -0.5], [-1, -1.5]]
""" """
if _check_not_integer(matrix_a) and _check_not_integer(matrix_b): if _check_not_integer(matrix_a)\
_verify_matrix_sizes(matrix_a, matrix_b) and _check_not_integer(matrix_b)\
and _verify_matrix_sizes(matrix_a, matrix_b):
return [[i - j for i, j in zip(*m)] for m in zip(matrix_a, matrix_b)] return [[i - j for i, j in zip(*m)] for m in zip(matrix_a, matrix_b)]
@ -49,25 +49,19 @@ def multiply(matrix_a: List[list], matrix_b: List[list]) -> List[list]:
[[19, 15], [43, 35]] [[19, 15], [43, 35]]
>>> multiply([[1,2.5],[3,4.5]],[[5,5],[7,5]]) >>> multiply([[1,2.5],[3,4.5]],[[5,5],[7,5]])
[[22.5, 17.5], [46.5, 37.5]] [[22.5, 17.5], [46.5, 37.5]]
>>> multiply([[1, 2, 3]], [[2], [3], [4]])
[[20]]
""" """
if _check_not_integer(matrix_a) and _check_not_integer(matrix_b): if _check_not_integer(matrix_a) and _check_not_integer(matrix_b):
matrix_c = []
rows, cols = _verify_matrix_sizes(matrix_a, matrix_b) rows, cols = _verify_matrix_sizes(matrix_a, matrix_b)
if cols[0] != rows[1]: if cols[0] != rows[1]:
raise ValueError( raise ValueError(
f"Cannot multiply matrix of dimensions ({rows[0]},{cols[0]}) " f"Cannot multiply matrix of dimensions ({rows[0]},{cols[0]}) "
f"and ({rows[1]},{cols[1]})" f"and ({rows[1]},{cols[1]})"
) )
for i in range(rows[0]): return [[sum(m * n for m, n in zip(i, j)) for j in zip(*matrix_b)]
list_1 = [] for i in matrix_a]
for j in range(cols[1]):
val = 0
for k in range(cols[1]):
val += matrix_a[i][k] * matrix_b[k][j]
list_1.append(val)
matrix_c.append(list_1)
return matrix_c
def identity(n: int) -> List[list]: def identity(n: int) -> List[list]:
@ -93,7 +87,7 @@ def transpose(matrix: List[list], return_map: bool = True) -> List[list]:
if return_map: if return_map:
return map(list, zip(*matrix)) return map(list, zip(*matrix))
else: else:
return [[row[i] for row in matrix] for i in range(len(matrix[0]))] return list(map(list, zip(*matrix)))
def minor(matrix: List[list], row: int, column: int) -> List[list]: def minor(matrix: List[list], row: int, column: int) -> List[list]:
@ -101,8 +95,8 @@ def minor(matrix: List[list], row: int, column: int) -> List[list]:
>>> minor([[1, 2], [3, 4]], 1, 1) >>> minor([[1, 2], [3, 4]], 1, 1)
[[1]] [[1]]
""" """
minor = matrix[:row] + matrix[row + 1 :] minor = matrix[: row] + matrix[row + 1:]
return [row[:column] + row[column + 1 :] for row in minor] return [row[:column] + row[column + 1:] for row in minor]
def determinant(matrix: List[list]) -> int: def determinant(matrix: List[list]) -> int:
@ -115,10 +109,8 @@ def determinant(matrix: List[list]) -> int:
if len(matrix) == 1: if len(matrix) == 1:
return matrix[0][0] return matrix[0][0]
res = 0 return sum(x * determinant(minor(matrix, 0, i)) * (-1) ** i
for x in range(len(matrix)): for i, x in enumerate(matrix[0]))
res += matrix[0][x] * determinant(minor(matrix, 0, x)) * (-1) ** x
return res
def inverse(matrix: List[list]) -> List[list]: def inverse(matrix: List[list]) -> List[list]:
@ -132,10 +124,9 @@ def inverse(matrix: List[list]) -> List[list]:
if det == 0: if det == 0:
return None return None
matrix_minor = [[] for _ in matrix] matrix_minor = [[determinant(minor(matrix, i, j))
for i in range(len(matrix)): for j in range(len(matrix))]
for j in range(len(matrix)): for i in range(len(matrix))]
matrix_minor[i].append(determinant(minor(matrix, i, j)))
cofactors = [ cofactors = [
[x * (-1) ** (row + col) for col, x in enumerate(matrix_minor[row])] [x * (-1) ** (row + col) for col, x in enumerate(matrix_minor[row])]
@ -152,29 +143,29 @@ def _check_not_integer(matrix: List[list]) -> bool:
def _shape(matrix: List[list]) -> list: def _shape(matrix: List[list]) -> list:
return list((len(matrix), len(matrix[0]))) return len(matrix), len(matrix[0])
def _verify_matrix_sizes(matrix_a: List[list], matrix_b: List[list]) -> Tuple[list]: def _verify_matrix_sizes(matrix_a: List[list], matrix_b: List[list]) -> Tuple[list]:
shape = _shape(matrix_a) shape = _shape(matrix_a) + _shape(matrix_b)
shape += _shape(matrix_b) if shape[0] != shape[3] or shape[1] != shape[2]:
if shape[0] != shape[2] or shape[1] != shape[3]:
raise ValueError( raise ValueError(
f"operands could not be broadcast together with shape " f"operands could not be broadcast together with shape "
f"({shape[0], shape[1]}), ({shape[2], shape[3]})" f"({shape[0], shape[1]}), ({shape[2], shape[3]})"
) )
return [shape[0], shape[2]], [shape[1], shape[3]] return (shape[0], shape[2]), (shape[1], shape[3])
def main(): def main():
matrix_a = [[12, 10], [3, 9]] matrix_a = [[12, 10], [3, 9]]
matrix_b = [[3, 4], [7, 4]] matrix_b = [[3, 4], [7, 4]]
matrix_c = [[11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34], [41, 42, 43, 44]] matrix_c = [[11, 12, 13, 14], [21, 22, 23, 24],
[31, 32, 33, 34], [41, 42, 43, 44]]
matrix_d = [[3, 0, 2], [2, 0, -2], [0, 1, 1]] matrix_d = [[3, 0, 2], [2, 0, -2], [0, 1, 1]]
print(f"Add Operation, {matrix_a} + {matrix_b} =" f"{add(matrix_a, matrix_b)} \n")
print( print(
f"Multiply Operation, {matrix_a} * {matrix_b}", f"Add Operation, {add(matrix_a, matrix_b) = } \n")
f"= {multiply(matrix_a, matrix_b)} \n", print(
f"Multiply Operation, {multiply(matrix_a, matrix_b) = } \n",
) )
print(f"Identity: {identity(5)}\n") print(f"Identity: {identity(5)}\n")
print(f"Minor of {matrix_c} = {minor(matrix_c, 1, 2)} \n") print(f"Minor of {matrix_c} = {minor(matrix_c, 1, 2)} \n")