Skip to content

matrixChainMultiplication in python is written #237

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
44 changes: 44 additions & 0 deletions Dynamic Programming/MatrixChainMuliplication.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#Matrix Chain Multiplication using dynamic programming approach
# A naive recursive implementation that
# simply follows the above optimal
# substructure property

import sys

# Matrix A[i] has dimension p[i-1] x p[i]
# for i = 1..n
def MatrixChainOrder(p, i, j):

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));


# code is contributed by Samya Subhro Roy :)