5
5
Implementation of Matrix Chain Multiplication
6
6
Time Complexity: O(n^3)
7
7
Space Complexity: O(n^2)
8
+
9
+ Reference: https://en.wikipedia.org/wiki/Matrix_chain_multiplication
8
10
"""
9
11
10
12
11
- def matrix_chain_order (array ):
13
+ def matrix_chain_order (array : list [int ]) -> tuple [list [list [int ]], list [list [int ]]]:
14
+ """
15
+ >>> matrix_chain_order([10, 30, 5])
16
+ ([[0, 0, 0], [0, 0, 1500], [0, 0, 0]], [[0, 0, 0], [0, 0, 1], [0, 0, 0]])
17
+ """
12
18
n = len (array )
13
- matrix = [[0 for x in range (n )] for x in range (n )]
14
- sol = [[0 for x in range (n )] for x in range (n )]
19
+ matrix = [[0 for _ in range (n )] for _ in range (n )]
20
+ sol = [[0 for _ in range (n )] for _ in range (n )]
15
21
16
22
for chain_length in range (2 , n ):
17
23
for a in range (1 , n - chain_length + 1 ):
@@ -28,26 +34,33 @@ def matrix_chain_order(array):
28
34
return matrix , sol
29
35
30
36
31
- # Print order of matrix with Ai as Matrix
32
- def print_optiomal_solution (optimal_solution , i , j ):
37
+ def print_optimal_solution (optimal_solution : list [list [int ]], i : int , j : int ):
38
+ """
39
+ Print order of matrix with Ai as Matrix.
40
+ """
41
+
33
42
if i == j :
34
43
print ("A" + str (i ), end = " " )
35
44
else :
36
45
print ("(" , end = " " )
37
- print_optiomal_solution (optimal_solution , i , optimal_solution [i ][j ])
38
- print_optiomal_solution (optimal_solution , optimal_solution [i ][j ] + 1 , j )
46
+ print_optimal_solution (optimal_solution , i , optimal_solution [i ][j ])
47
+ print_optimal_solution (optimal_solution , optimal_solution [i ][j ] + 1 , j )
39
48
print (")" , end = " " )
40
49
41
50
42
51
def main ():
52
+ """
53
+ Size of matrix created from array [30, 35, 15, 5, 10, 20, 25] will be:
54
+ 30*35 35*15 15*5 5*10 10*20 20*25
55
+ """
56
+
43
57
array = [30 , 35 , 15 , 5 , 10 , 20 , 25 ]
44
58
n = len (array )
45
- # Size of matrix created from above array will be
46
- # 30*35 35*15 15*5 5*10 10*20 20*25
59
+
47
60
matrix , optimal_solution = matrix_chain_order (array )
48
61
49
62
print ("No. of Operation required: " + str (matrix [1 ][n - 1 ]))
50
- print_optiomal_solution (optimal_solution , 1 , n - 1 )
63
+ print_optimal_solution (optimal_solution , 1 , n - 1 )
51
64
52
65
53
66
if __name__ == "__main__" :
0 commit comments