Summary - Matrix chain
- Algorithms course
- Advanced
- Lesson 24/56
- 4 min
Print the minimum multiplication cost in a mini task.
Summary - Matrix chain
In this group you learned to find the lowest cost of matrix chain multiplication with dynamic programming. Dimension array, DP table and split point combine into the solution.
Now you will write a function that brings all pieces together. This summary unites the group's concepts in a single piece of code.
Practice min_chain_cost function
Write min_chain_cost(dims). Build the DP table, fill it with nested loops and return m[1][n-1]. Print 18000 with print(min_chain_cost([10, 20, 30, 40])).
Starter code
def min_chain_cost(dims):
# Find lowest cost with DPSample solution
def min_chain_cost(dims):
# Find lowest cost with DP
n = len(dims)
m = [[0] * n for _ in range(n)]
for length in range(2, n):
for i in range(1, n - length + 1):
j = i + length - 1
m[i][j] = float('inf')
for k in range(i, j):
cost = m[i][k] + m[k + 1][j] + dims[i - 1] * dims[k] * dims[j]
if cost < m[i][j]:
m[i][j] = cost
return m[1][n - 1]
print(min_chain_cost([10, 20, 30, 40]))Expected output
18000
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which table cell does matrix_chain return?
- m[0][0]
- m[0][n]
- m[n][n]
- m[1][n-1] Correct answer
Explanation: m[1][n-1] is the cost of the whole chain.
2 Dimension array
dims = init_____()
dims = init_dims()
Explanation: dims is right.
3 Summary - Matrix chain: match the terms
| Term | Meaning |
|---|---|
init_dims |
Dimension |
init_table |
Table |
matrix_chain |
Cost |
k |
Split |