Python/dynamic_programming/matrix_chain_order.py

55 lines
1.5 KiB
Python
Raw Normal View History

2018-02-26 11:55:09 +00:00
import sys
2019-10-05 05:14:13 +00:00
"""
2018-02-26 11:55:09 +00:00
Dynamic Programming
Implementation of Matrix Chain Multiplication
Time Complexity: O(n^3)
Space Complexity: O(n^2)
2019-10-05 05:14:13 +00:00
"""
2018-02-26 11:55:09 +00:00
def MatrixChainOrder(array):
2019-10-05 05:14:13 +00:00
N = len(array)
Matrix = [[0 for x in range(N)] for x in range(N)]
Sol = [[0 for x in range(N)] for x in range(N)]
2018-02-26 11:55:09 +00:00
2019-10-05 05:14:13 +00:00
for ChainLength in range(2, N):
for a in range(1, N - ChainLength + 1):
b = a + ChainLength - 1
2018-02-26 11:55:09 +00:00
Matrix[a][b] = sys.maxsize
2019-10-05 05:14:13 +00:00
for c in range(a, b):
cost = (
Matrix[a][c] + Matrix[c + 1][b] + array[a - 1] * array[c] * array[b]
)
2018-02-26 11:55:09 +00:00
if cost < Matrix[a][b]:
Matrix[a][b] = cost
Sol[a][b] = c
2019-10-05 05:14:13 +00:00
return Matrix, Sol
# Print order of matrix with Ai as Matrix
def PrintOptimalSolution(OptimalSolution, i, j):
if i == j:
print("A" + str(i), end=" ")
2018-02-26 11:55:09 +00:00
else:
2019-10-05 05:14:13 +00:00
print("(", end=" ")
PrintOptimalSolution(OptimalSolution, i, OptimalSolution[i][j])
PrintOptimalSolution(OptimalSolution, OptimalSolution[i][j] + 1, j)
print(")", end=" ")
2018-02-26 11:55:09 +00:00
def main():
2019-10-05 05:14:13 +00:00
array = [30, 35, 15, 5, 10, 20, 25]
n = len(array)
# Size of matrix created from above array will be
2018-02-26 11:55:09 +00:00
# 30*35 35*15 15*5 5*10 10*20 20*25
2019-10-05 05:14:13 +00:00
Matrix, OptimalSolution = MatrixChainOrder(array)
print("No. of Operation required: " + str(Matrix[1][n - 1]))
2019-10-05 05:14:13 +00:00
PrintOptimalSolution(OptimalSolution, 1, n - 1)
2018-02-26 11:55:09 +00:00
2019-10-05 05:14:13 +00:00
if __name__ == "__main__":
2018-02-26 11:55:09 +00:00
main()