55Implementation of Matrix Chain Multiplication
66Time Complexity: O(n^3)
77Space Complexity: O(n^2)
8+
9+ Reference: https://en.wikipedia.org/wiki/Matrix_chain_multiplication
810"""
911
1012
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+ """
1218 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 )]
1521
1622 for chain_length in range (2 , n ):
1723 for a in range (1 , n - chain_length + 1 ):
@@ -28,26 +34,33 @@ def matrix_chain_order(array):
2834 return matrix , sol
2935
3036
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+
3342 if i == j :
3443 print ("A" + str (i ), end = " " )
3544 else :
3645 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 )
3948 print (")" , end = " " )
4049
4150
4251def 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+
4357 array = [30 , 35 , 15 , 5 , 10 , 20 , 25 ]
4458 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+
4760 matrix , optimal_solution = matrix_chain_order (array )
4861
4962 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 )
5164
5265
5366if __name__ == "__main__" :
0 commit comments