Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 2a00125

Browse filesBrowse files
mujtaba1747abranhe
authored andcommitted
Added Matrix Chain Multiplication in Python
1 parent 0de78cb commit 2a00125
Copy full SHA for 2a00125

File tree

Expand file treeCollapse file tree

1 file changed

+39
-0
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+39
-0
lines changed
+39Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Python program to solve Matrix chain multiplication using Dynamic Programming
2+
# MatrixChain returns the minimum number of scalar multiplications needed to
3+
# Compute the product of the chain
4+
import sys
5+
# Matrix Ai has dimension p[i-1] x p[i] for i = 1..n
6+
def MatrixChain(p, n):
7+
# For simplicity of the program, one extra row and one
8+
# extra column are allocated in m[][]. 0th row and 0th
9+
# column of m[][] are not used
10+
m = [[0 for x in range(n)] for x in range(n)]
11+
12+
# m[i, j] = Minimum number of scalar multiplications needed
13+
# to compute the matrix A[i]A[i + 1]...A[j] = A[i..j] where
14+
# dimension of A[i] is p[i-1] x p[i]
15+
16+
# cost is zero when multiplying one matrix.
17+
for i in range(1, n):
18+
m[i][i] = 0
19+
20+
# L is chain length.
21+
for L in range(2, n):
22+
for i in range(1, n-L + 1):
23+
j = i + L-1
24+
m[i][j] = sys.maxsize # sys.maxsize is a very large integer value (Refer https://stackoverflow.com/questions/48138632/in-python-what-is-sys-maxsize for more details if intrested)
25+
for k in range(i, j):
26+
27+
# q = cost / scalar multiplications
28+
q = m[i][k] + m[k + 1][j] + p[i-1]*p[k]*p[j]
29+
if q < m[i][j]:
30+
m[i][j] = q
31+
32+
return m[1][n-1]
33+
34+
# Program to test above function
35+
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
36+
size = len(arr)
37+
38+
print("Minimum number of multiplications is " +
39+
str(MatrixChain(arr, size)))

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.