Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 23 additions & 10 deletions dynamic_programming/matrix_chain_order.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,19 @@
Implementation of Matrix Chain Multiplication
Time Complexity: O(n^3)
Space Complexity: O(n^2)

Reference: https://en.wikipedia.org/wiki/Matrix_chain_multiplication
"""


def matrix_chain_order(array):
def matrix_chain_order(array: list[int]) -> tuple[list[list[int]], list[list[int]]]:
"""
>>> matrix_chain_order([10, 30, 5])
([[0, 0, 0], [0, 0, 1500], [0, 0, 0]], [[0, 0, 0], [0, 0, 1], [0, 0, 0]])
"""
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)]
matrix = [[0 for _ in range(n)] for _ in range(n)]
sol = [[0 for _ in range(n)] for _ in range(n)]

for chain_length in range(2, n):
for a in range(1, n - chain_length + 1):
Expand All @@ -28,26 +34,33 @@ def matrix_chain_order(array):
return matrix, sol


# Print order of matrix with Ai as Matrix
def print_optiomal_solution(optimal_solution, i, j):
def print_optimal_solution(optimal_solution: list[list[int]], i: int, j: int):
"""
Print order of matrix with Ai as Matrix.
"""

if i == j:
print("A" + str(i), end=" ")
else:
print("(", end=" ")
print_optiomal_solution(optimal_solution, i, optimal_solution[i][j])
print_optiomal_solution(optimal_solution, optimal_solution[i][j] + 1, j)
print_optimal_solution(optimal_solution, i, optimal_solution[i][j])
print_optimal_solution(optimal_solution, optimal_solution[i][j] + 1, j)
print(")", end=" ")


def main():
"""
Size of matrix created from array [30, 35, 15, 5, 10, 20, 25] will be:
30*35 35*15 15*5 5*10 10*20 20*25
"""

array = [30, 35, 15, 5, 10, 20, 25]
n = len(array)
# Size of matrix created from above array will be
# 30*35 35*15 15*5 5*10 10*20 20*25

matrix, optimal_solution = matrix_chain_order(array)

print("No. of Operation required: " + str(matrix[1][n - 1]))
print_optiomal_solution(optimal_solution, 1, n - 1)
print_optimal_solution(optimal_solution, 1, n - 1)


if __name__ == "__main__":
Expand Down