Skip to content

Commit 67cbe42

Browse files
committed
Create matrix_chain.py
Mtraix chain multiplication, finding the min number of multiplication in a chain
1 parent c7375ba commit 67cbe42

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

TextProcessingChpt/matrix_chain.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
2+
# from typing import List
3+
# import math
4+
5+
def matrix_chain(d):
6+
""" d is a list of n+1 numbers such that size of kth matrix
7+
id d[k] by d[k+1]
8+
9+
Return a n by n table such that N[i][j] represents the min number
10+
of multiplications needed to compute the product of Ai through Aj inclusive"""
11+
12+
n = len(d) - 1 # number of matrices
13+
N = [[0] * n for i in range(n)] # initilialize n by n result to 0
14+
15+
for b in range(1, n): #number of products in subchain
16+
for i in range(n-b): # start of subchain
17+
j = i + b
18+
N[i][j] = min(N[i][k] + N[k+1][j] + d[i] * d[k+1] * d[j+1] for k in range(i, j))
19+
20+
return N #or N[0][n-1]
21+
# A leetcode solution
22+
# def minScoreTriangulation( A: List[int]) -> int:
23+
# SP, L = [[0]*50 for _ in range(50)], len(A)
24+
# for i in range(2,L):
25+
# for j in range(L-i):
26+
# s, e, SP[s][e] = j, j + i, math.inf
27+
# for k in range(s+1,e): SP[s][e] = min(SP[s][e], A[s]*A[k]*A[e] + SP[s][k] + SP[k][e])
28+
# return SP[0][L-1]
29+
30+
array = [2,3,4]
31+
print(matrix_chain(array))
32+
# print(minScoreTriangulation(array))

0 commit comments

Comments
 (0)