Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Matrix chain multiplication #285

Closed
wants to merge 8 commits into from
Closed
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
35 changes: 35 additions & 0 deletions pydatastructs/MATRIX_CHAIN_MULTIPLICATION.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Matrix Mi has dimension
// p[i-1] x p[i] for i = 1..n
def MatrixChainOrder(p, n):

// For simplicity of the program, one
/ extra row and one extra column are
// allocated in dp[][]. 0th row and
// 0th column of dp[][] are not used
dp = [[0 for i in range(n)]
for i in range(n)]

// dp[i, j] = Minimum number of scalar
// multiplications needed to compute
// the matrix M[i]M[i+1]...M[j] = M[i..j]
// where dimension of M[i] is p[i-1] x p[i]

// cost is zero when multiplying one matrix.
for i in range(1, n):
dp[i][i] = 0

// Simply following above recursive formula.
for L in range(1, n - 1):
for i in range(n - L):
dp[i][i + L] = min(dp[i + 1][i + L] +
p[i - 1] * p[i] * p[i + L],
dp[i][i + L - 1] +
p[i - 1] * p[i + L - 1] * p[i + L])

return dp[1][n - 1]

// Driver code
arr = [10, 20, 30, 40, 30]
size = len(arr)
print("Minimum number of multiplications is",
MatrixChainOrder(arr, size))