-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathmatrixchain_mul.py
More file actions
35 lines (25 loc) · 782 Bytes
/
matrixchain_mul.py
File metadata and controls
35 lines (25 loc) · 782 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import sys
def MatrixChainOrder(p, i, j):
'''
Matrix A[i] has dimension p[i-1] x p[i]
for i = 1..n
'''
if i == j:
return 0
_min = sys.maxsize
# place parenthesis at different places
# between first and last matrix,
# recursively calculate count of
# multiplications for each parenthesis
# placement and return the minimum count
for k in range(i, j):
count = (MatrixChainOrder(p, i, k) + MatrixChainOrder(p, k + 1, j) +
p[i - 1] * p[k] * p[j])
if count < _min:
_min = count
# Return minimum count
return _min
# Driver program to test above function
arr = [1, 2, 3, 4, 3]
n = len(arr)
print("Minimum number of multiplications is ", MatrixChainOrder(arr, 1, n - 1))