Skip to content

Commit 6822d1a

Browse files
author
wuyudi
authored
Update matrix_operation.py (TheAlgorithms#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
1 parent ae33419 commit 6822d1a

File tree

1 file changed

+31
-40
lines changed

1 file changed

+31
-40
lines changed

matrix/matrix_operation.py

Lines changed: 31 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,8 @@ def add(*matrix_s: List[list]) -> List[list]:
1515
[[7, 14], [12, 16]]
1616
"""
1717
if all(_check_not_integer(m) for m in matrix_s):
18-
a, *b = matrix_s
19-
for matrix in b:
20-
_verify_matrix_sizes(a, matrix)
18+
for i in matrix_s[1:]:
19+
_verify_matrix_sizes(matrix_s[0], i)
2120
return [[sum(t) for t in zip(*m)] for m in zip(*matrix_s)]
2221

2322

@@ -28,8 +27,9 @@ def subtract(matrix_a: List[list], matrix_b: List[list]) -> List[list]:
2827
>>> subtract([[1,2.5],[3,4]],[[2,3],[4,5.5]])
2928
[[-1, -0.5], [-1, -1.5]]
3029
"""
31-
if _check_not_integer(matrix_a) and _check_not_integer(matrix_b):
32-
_verify_matrix_sizes(matrix_a, matrix_b)
30+
if _check_not_integer(matrix_a)\
31+
and _check_not_integer(matrix_b)\
32+
and _verify_matrix_sizes(matrix_a, matrix_b):
3333
return [[i - j for i, j in zip(*m)] for m in zip(matrix_a, matrix_b)]
3434

3535

@@ -49,25 +49,19 @@ def multiply(matrix_a: List[list], matrix_b: List[list]) -> List[list]:
4949
[[19, 15], [43, 35]]
5050
>>> multiply([[1,2.5],[3,4.5]],[[5,5],[7,5]])
5151
[[22.5, 17.5], [46.5, 37.5]]
52+
>>> multiply([[1, 2, 3]], [[2], [3], [4]])
53+
[[20]]
5254
"""
5355
if _check_not_integer(matrix_a) and _check_not_integer(matrix_b):
54-
matrix_c = []
5556
rows, cols = _verify_matrix_sizes(matrix_a, matrix_b)
5657

57-
if cols[0] != rows[1]:
58-
raise ValueError(
59-
f"Cannot multiply matrix of dimensions ({rows[0]},{cols[0]}) "
60-
f"and ({rows[1]},{cols[1]})"
61-
)
62-
for i in range(rows[0]):
63-
list_1 = []
64-
for j in range(cols[1]):
65-
val = 0
66-
for k in range(cols[1]):
67-
val += matrix_a[i][k] * matrix_b[k][j]
68-
list_1.append(val)
69-
matrix_c.append(list_1)
70-
return matrix_c
58+
if cols[0] != rows[1]:
59+
raise ValueError(
60+
f"Cannot multiply matrix of dimensions ({rows[0]},{cols[0]}) "
61+
f"and ({rows[1]},{cols[1]})"
62+
)
63+
return [[sum(m * n for m, n in zip(i, j)) for j in zip(*matrix_b)]
64+
for i in matrix_a]
7165

7266

7367
def identity(n: int) -> List[list]:
@@ -93,16 +87,16 @@ def transpose(matrix: List[list], return_map: bool = True) -> List[list]:
9387
if return_map:
9488
return map(list, zip(*matrix))
9589
else:
96-
return [[row[i] for row in matrix] for i in range(len(matrix[0]))]
90+
return list(map(list, zip(*matrix)))
9791

9892

9993
def minor(matrix: List[list], row: int, column: int) -> List[list]:
10094
"""
10195
>>> minor([[1, 2], [3, 4]], 1, 1)
10296
[[1]]
10397
"""
104-
minor = matrix[:row] + matrix[row + 1 :]
105-
return [row[:column] + row[column + 1 :] for row in minor]
98+
minor = matrix[: row] + matrix[row + 1:]
99+
return [row[:column] + row[column + 1:] for row in minor]
106100

107101

108102
def determinant(matrix: List[list]) -> int:
@@ -115,10 +109,8 @@ def determinant(matrix: List[list]) -> int:
115109
if len(matrix) == 1:
116110
return matrix[0][0]
117111

118-
res = 0
119-
for x in range(len(matrix)):
120-
res += matrix[0][x] * determinant(minor(matrix, 0, x)) * (-1) ** x
121-
return res
112+
return sum(x * determinant(minor(matrix, 0, i)) * (-1) ** i
113+
for i, x in enumerate(matrix[0]))
122114

123115

124116
def inverse(matrix: List[list]) -> List[list]:
@@ -132,10 +124,9 @@ def inverse(matrix: List[list]) -> List[list]:
132124
if det == 0:
133125
return None
134126

135-
matrix_minor = [[] for _ in matrix]
136-
for i in range(len(matrix)):
137-
for j in range(len(matrix)):
138-
matrix_minor[i].append(determinant(minor(matrix, i, j)))
127+
matrix_minor = [[determinant(minor(matrix, i, j))
128+
for j in range(len(matrix))]
129+
for i in range(len(matrix))]
139130

140131
cofactors = [
141132
[x * (-1) ** (row + col) for col, x in enumerate(matrix_minor[row])]
@@ -152,29 +143,29 @@ def _check_not_integer(matrix: List[list]) -> bool:
152143

153144

154145
def _shape(matrix: List[list]) -> list:
155-
return list((len(matrix), len(matrix[0])))
146+
return len(matrix), len(matrix[0])
156147

157148

158149
def _verify_matrix_sizes(matrix_a: List[list], matrix_b: List[list]) -> Tuple[list]:
159-
shape = _shape(matrix_a)
160-
shape += _shape(matrix_b)
161-
if shape[0] != shape[2] or shape[1] != shape[3]:
150+
shape = _shape(matrix_a) + _shape(matrix_b)
151+
if shape[0] != shape[3] or shape[1] != shape[2]:
162152
raise ValueError(
163153
f"operands could not be broadcast together with shape "
164154
f"({shape[0], shape[1]}), ({shape[2], shape[3]})"
165155
)
166-
return [shape[0], shape[2]], [shape[1], shape[3]]
156+
return (shape[0], shape[2]), (shape[1], shape[3])
167157

168158

169159
def main():
170160
matrix_a = [[12, 10], [3, 9]]
171161
matrix_b = [[3, 4], [7, 4]]
172-
matrix_c = [[11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34], [41, 42, 43, 44]]
162+
matrix_c = [[11, 12, 13, 14], [21, 22, 23, 24],
163+
[31, 32, 33, 34], [41, 42, 43, 44]]
173164
matrix_d = [[3, 0, 2], [2, 0, -2], [0, 1, 1]]
174-
print(f"Add Operation, {matrix_a} + {matrix_b} =" f"{add(matrix_a, matrix_b)} \n")
175165
print(
176-
f"Multiply Operation, {matrix_a} * {matrix_b}",
177-
f"= {multiply(matrix_a, matrix_b)} \n",
166+
f"Add Operation, {add(matrix_a, matrix_b) = } \n")
167+
print(
168+
f"Multiply Operation, {multiply(matrix_a, matrix_b) = } \n",
178169
)
179170
print(f"Identity: {identity(5)}\n")
180171
print(f"Minor of {matrix_c} = {minor(matrix_c, 1, 2)} \n")

0 commit comments

Comments
 (0)