MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / matrix_multiply_recursive

Function matrix_multiply_recursive

matrix/matrix_multiplication_recursion.py:82–148  ·  view source on GitHub ↗

:param matrix_a: A square Matrix. :param matrix_b: Another square Matrix with the same dimensions as matrix_a. :return: Result of matrix_a * matrix_b. :raises ValueError: If the matrices cannot be multiplied. >>> matrix_multiply_recursive([], []) [] >>> matrix_multiply_

(matrix_a: Matrix, matrix_b: Matrix)

Source from the content-addressed store, hash-verified

80
81
82def matrix_multiply_recursive(matrix_a: Matrix, matrix_b: Matrix) -> Matrix:
83 """
84 :param matrix_a: A square Matrix.
85 :param matrix_b: Another square Matrix with the same dimensions as matrix_a.
86 :return: Result of matrix_a * matrix_b.
87 :raises ValueError: If the matrices cannot be multiplied.
88
89 >>> matrix_multiply_recursive([], [])
90 []
91 >>> matrix_multiply_recursive(matrix_1_to_4, matrix_5_to_8)
92 [[19, 22], [43, 50]]
93 >>> matrix_multiply_recursive(matrix_count_up, matrix_unordered)
94 [[37, 61, 74, 61], [105, 165, 166, 129], [173, 269, 258, 197], [241, 373, 350, 265]]
95 >>> matrix_multiply_recursive(matrix_1_to_4, matrix_5_to_9_wide)
96 Traceback (most recent call last):
97 ...
98 ValueError: Invalid matrix dimensions
99 >>> matrix_multiply_recursive(matrix_1_to_4, matrix_5_to_9_high)
100 Traceback (most recent call last):
101 ...
102 ValueError: Invalid matrix dimensions
103 >>> matrix_multiply_recursive(matrix_1_to_4, matrix_count_up)
104 Traceback (most recent call last):
105 ...
106 ValueError: Invalid matrix dimensions
107 """
108 if not matrix_a or not matrix_b:
109 return []
110 if not all(
111 (len(matrix_a) == len(matrix_b), is_square(matrix_a), is_square(matrix_b))
112 ):
113 raise ValueError("Invalid matrix dimensions")
114
115 # Initialize the result matrix with zeros
116 result = [[0] * len(matrix_b[0]) for _ in range(len(matrix_a))]
117
118 # Recursive multiplication of matrices
119 def multiply(
120 i_loop: int,
121 j_loop: int,
122 k_loop: int,
123 matrix_a: Matrix,
124 matrix_b: Matrix,
125 result: Matrix,
126 ) -> None:
127 """
128 :param matrix_a: A square Matrix.
129 :param matrix_b: Another square Matrix with the same dimensions as matrix_a.
130 :param result: Result matrix
131 :param i: Index used for iteration during multiplication.
132 :param j: Index used for iteration during multiplication.
133 :param k: Index used for iteration during multiplication.
134 >>> 0 > 1 # Doctests in inner functions are never run
135 True
136 """
137 if i_loop >= len(matrix_a):
138 return
139 if j_loop >= len(matrix_b[0]):

Calls 2

is_squareFunction · 0.85
multiplyFunction · 0.70

Tested by

no test coverage detected