-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path100-matrix_mul.py
67 lines (55 loc) · 2.33 KB
/
100-matrix_mul.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#!/usr/bin/python3
"""Defines a matrix multiplication function."""
def matrix_mul(m_a, m_b):
"""Multiply two matrices.
Args:
m_a (list of lists of ints/floats): The first matrix.
m_b (list of lists of ints/floats): The second matrix.
Raises:
TypeError: If either m_a or m_b is not a list of lists of ints/floats.
TypeError: If either m_a or m_b is empty.
TypeError: If either m_a or m_b has different-sized rows.
ValueError: If m_a and m_b cannot be multiplied.
Returns:
A new matrix representing the multiplication of m_a by m_b.
"""
if m_a == [] or m_a == [[]]:
raise ValueError("m_a can't be empty")
if m_b == [] or m_b == [[]]:
raise ValueError("m_b can't be empty")
if not isinstance(m_a, list):
raise TypeError("m_a must be a list")
if not isinstance(m_b, list):
raise TypeError("m_b must be a list")
if not all(isinstance(row, list) for row in m_a):
raise TypeError("m_a must be a list of lists")
if not all(isinstance(row, list) for row in m_b):
raise TypeError("m_b must be a list of lists")
if not all((isinstance(ele, int) or isinstance(ele, float))
for ele in [num for row in m_a for num in row]):
raise TypeError("m_a should contain only integers or floats")
if not all((isinstance(ele, int) or isinstance(ele, float))
for ele in [num for row in m_b for num in row]):
raise TypeError("m_b should contain only integers or floats")
if not all(len(row) == len(m_a[0]) for row in m_a):
raise TypeError("each row of m_a must should be of the same size")
if not all(len(row) == len(m_b[0]) for row in m_b):
raise TypeError("each row of m_b must should be of the same size")
if len(m_a[0]) != len(m_b):
raise ValueError("m_a and m_b can't be multiplied")
inverted_b = []
for r in range(len(m_b[0])):
new_row = []
for c in range(len(m_b)):
new_row.append(m_b[c][r])
inverted_b.append(new_row)
new_matrix = []
for row in m_a:
new_row = []
for col in inverted_b:
prod = 0
for i in range(len(inverted_b[0])):
prod += row[i] * col[i]
new_row.append(prod)
new_matrix.append(new_row)
return new_matrix