The Wayback Machine - https://web.archive.org/web/20240817182756/https://www.geeksforgeeks.org/python-program-for-matrix-chain-multiplication-dp-8/
Open In App

Python Program for Matrix Chain Multiplication | DP-8

Last Updated : 20 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a sequence of matrices, find the most efficient way to multiply these matrices together. The problem is not actually to perform the multiplications, but merely to decide in which order to perform the multiplications. We have many options to multiply a chain of matrices because matrix multiplication is associative. In other words, no matter how we parenthesize the product, the result will be the same. For example, if we had four matrices A, B, C, and D, we would have:

    (ABC)D = (AB)(CD) = A(BCD) = ....

However, the order in which we parenthesize the product affects the number of simple arithmetic operations needed to compute the product or the efficiency. For example, suppose A is a 10 × 30 matrix, B is a 30 × 5 matrix, and C is a 5 × 60 matrix. Then,

    (AB)C = (10×30×5) + (10×5×60) = 1500 + 3000 = 4500 operations
    A(BC) = (30×5×60) + (10×30×60) = 9000 + 18000 = 27000 operations.

Clearly, the first parenthesization requires less number of operations. Given an array p[] which represents the chain of matrices such that the ith matrix Ai is of dimension p[i-1] x p[i]. We need to write a function MatrixChainOrder() that should return the minimum number of multiplications needed to multiply the chain.

  Input: p[] = {40, 20, 30, 10, 30}   
  Output: 26000  
  There are 4 matrices of dimensions 40x20, 20x30, 30x10 and 10x30.
  Let the input 4 matrices be A, B, C and D.  The minimum number of 
  multiplications are obtained by putting parenthesis in following way
  (A(BC))D --> 20*30*10 + 40*20*10 + 40*10*30

  Input: p[] = {10, 20, 30, 40, 30} 
  Output: 30000 
  There are 4 matrices of dimensions 10x20, 20x30, 30x40 and 40x30. 
  Let the input 4 matrices be A, B, C and D.  The minimum number of 
  multiplications are obtained by putting parenthesis in following way
  ((AB)C)D --> 10*20*30 + 10*30*40 + 10*40*30

  Input: p[] = {10, 20, 30}  
  Output: 6000  
  There are only two matrices of dimensions 10x20 and 20x30. So there 
  is only one way to multiply the matrices, cost of which is 10*20*30

Following is a recursive implementation that simply follows the above optimal substructure property. 

Python3




# 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));
 
# This code is contributed by Aryan Garg


Output

Minimum number of multiplications is  30

Time complexity: The time complexity of the algorithm is O(n^3) where n is the number of matrices in the chain. This is because we have three nested loops and each loop runs n times.

Space complexity: The space complexity of the algorithm is O(n^2) because we are using a two-dimensional array to store the intermediate results. The size of the array is n x n.

Dynamic Programming Solution 

Python




# Dynamic Programming Python implementation of Matrix
# Chain Multiplication. See the Cormen book for details
# of the following algorithm
import sys
 
# Matrix Ai 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 m[][].  0th row and 0th
    # column of m[][] are not used
    m = [[0 for x in range(n)] for x in range(n)]
 
    # m[i, j] = Minimum number of scalar multiplications needed
    # to compute the matrix A[i]A[i + 1]...A[j] = A[i..j] where
    # dimension of A[i] is p[i-1] x p[i]
 
    # cost is zero when multiplying one matrix.
    for i in range(1, n):
        m[i][i] = 0
 
    # L is chain length.
    for L in range(2, n):
        for i in range(1, n-L + 1):
            j = i + L-1
            m[i][j] = sys.maxsize
            for k in range(i, j):
 
                # q = cost / scalar multiplications
                q = m[i][k] + m[k + 1][j] + p[i-1]*p[k]*p[j]
                if q < m[i][j]:
                    m[i][j] = q
 
    return m[1][n-1]
 
# Driver program to test above function
arr = [1, 2, 3, 4, 3]
size = len(arr)
 
print("Minimum number of multiplications is " +
       str(MatrixChainOrder(arr, size)))
# This Code is contributed by Bhavya Jain


Output

Minimum number of multiplications is 30

Please refer complete article on Matrix Chain Multiplication | DP-8 for more details!



Previous Article
Next Article

Similar Reads

Python program for multiplication and division of complex number
Given two complex numbers. The task is to multiply and divide them. Multiplication of complex number: In Python complex numbers can be multiplied using * operator Examples: Input: 2+3i, 4+5i Output: Multiplication is : (-7+22j) Input: 2+3i, 1+2i Output: Multiplication is : (-4+7j) C/C++ Code # Python program to demonstrate # multiplication of compl
3 min read
Python Program for Find remainder of array multiplication divided by n
Write a Python program for a given multiple numbers and a number n, the task is to print the remainder after multiplying all the numbers divided by n. Examples: Input: arr[] = {100, 10, 5, 25, 35, 14}, n = 11Output: 9Explanation: 100 x 10 x 5 x 25 x 35 x 14 = 61250000 % 11 = 9Input : arr[] = {100, 10}, n = 5 Output : 0Explanation: 100 x 10 = 1000 %
3 min read
Python program to Convert a Matrix to Sparse Matrix
Given a matrix with most of its elements as 0, we need to convert this matrix into a sparse matrix in Python. Example: Input: Matrix: 1 0 0 0 0 2 0 0 0 0 3 0 0 0 0 4 5 0 0 0 Output: Sparse Matrix: 0 0 1 1 1 2 2 2 3 3 3 4 4 0 5 Explanation: Here the Matrix is represented using a 2D list and the Sparse Matrix is represented in the form Row Column Val
3 min read
Python Program to Convert String Matrix Representation to Matrix
Given a String with matrix representation, the task here is to write a python program that converts it to a matrix. Input : test_str = "[gfg,is],[best,for],[all,geeks]"Output : [['gfg', 'is'], ['best', 'for'], ['all', 'geeks']]Explanation : Required String Matrix is converted to Matrix with list as data type. Input : test_str = "[gfg,is],[for],[all
4 min read
Python | Custom Multiplication in list of lists
Sometimes, when we are fed with the list of list, we need to multiply each of its element list with a particular element fed by the order in the other list. This particular problem is very specific but knowledge of it can be useful in such cases. Let's discuss certain ways in which this can be done. Method #1: Using loops This is the Naive and brut
8 min read
Python | Tuple multiplication
Sometimes, while working with records, we can have a problem in which we may need to perform multiplication of tuples. This problem can occur in day-day programming. Let's discuss certain ways in which this task can be performed. Method #1 : Using zip() + generator expression The combination of above functions can be used to perform this task. In t
5 min read
Python - Constant Multiplication over List
While working with the python lists, we can come over a situation in which we require to multiply constant to each element in the list. We possibly need to iterate and multiply constant to each element but that would increase the line of code. Let’s discuss certain shorthands to perform this task. Method #1 : Using List Comprehension List comprehen
6 min read
Python | Tuple list cross multiplication
Sometimes, while working with Python records, we can have a problem in which we need to perform cross multiplication of list of tuples. This kind of application is popular in web development domain. Let’s discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + zip() The combination of the above functionaliti
5 min read
Python - Constant Multiplication to Nth Column
Many times, while working with records, we can have a problem in which we need to change the value of tuple elements. This is a common problem while working with tuples. Let’s discuss certain ways in which K can be multiplied to Nth element of tuple in list. Method #1 : Using loop Using loops this task can be performed. In this, we just iterate the
7 min read
Python | Multiplication till Null value
The prefix array is quite famous in the programming world. This article would discuss a variation of this scheme. This deals with the cumulative list product till a False value, and again starts cumulation of product from occurrence of True value. Let’s discuss certain way in which this can be performed. Method #1 : Using Naive Method In the naive
4 min read
Python - Unique values Multiplication
This article focuses on one of the operation of getting the unique list from a list that contains a possible duplicates and performing its product. This operations has large no. of applications and hence it’s knowledge is good to have. Method 1 : Naive method + loop In naive method, we simply traverse the list and append the first occurrence of the
5 min read
Python - Multiplication across Like Keys Value list elements
Given two dictionaries with value lists, perform element wise like keys multiplication. Input : test_dict1 = {"Gfg" : [4, 6], "Best" : [8, 6], "is" : [9, 3]}, test_dict2 = {"Gfg": [8, 4], "Best" : [6, 3], "is" : [9, 8]} Output : {'Gfg': [32, 24], 'Best': [48, 18], 'is': [81, 24]} Explanation : 4 * 8 = 32, 6 * 4 = 24 and so on, hence new list value.
9 min read
Reverse Multiplication Table Using For loop in Python
A multiplication table of any number can be printed using the For loop in Python. We can also print the multiplication table in reverse order using a for loop in Python. In this article, we will see how we can print the multiplication table in reverse order using a for loop in Python. Example: Input: TableNumber = 2Output:Printing Multiplication Ta
3 min read
Multiplication Table Using While Loop in Python
Multiplication tables are fundamental in mathematics, serving as the building blocks for more advanced concepts. In Python, we can use various methods to generate multiplication tables, and one versatile tool for this task is the 'while' loop. In this article, we will explore some commonly used and straightforward methods to create multiplication t
3 min read
Python Program for Program to Print Matrix in Z form
Given a square matrix of order n*n, we need to print elements of the matrix in Z form Examples: Input : mat[][] = {1, 2, 3, 4, 5, 6, 7, 8, 9} Output : 1 2 3 5 7 8 9Input : mat[][] = {5, 19, 8, 7, 4, 1, 14, 8, 2, 20, 1, 9, 1, 2, 55, 4} Output: 5 19 8 7 14 20 1 2 55 4 C/C++ Code # Python program to print a # square matrix in Z form arr = [[4, 5, 6, 8
2 min read
Python - Convert Matrix to Custom Tuple Matrix
Sometimes, while working with Python Matrix, we can have a problem in which we need to perform conversion of a Python Matrix to matrix of tuples which a value attached row-wise custom from external list. This kind of problem can have applications in data domains as Matrix is integral DS that is used. Let's discuss certain ways in which this task ca
6 min read
Python - Convert Integer Matrix to String Matrix
Given a matrix with integer values, convert each element to String. Input : test_list = [[4, 5, 7], [10, 8, 3], [19, 4, 6]] Output : [['4', '5', '7'], ['10', '8', '3'], ['19', '4', '6']] Explanation : All elements of Matrix converted to Strings. Input : test_list = [[4, 5, 7], [10, 8, 3]] Output : [['4', '5', '7'], ['10', '8', '3']] Explanation : A
6 min read
Create an n x n square matrix, where all the sub-matrix have the sum of opposite corner elements as even
Given an integer N. The task is to generate a square matrix of ( n x n ) having the elements ranging from 1 to n^2 with the following condition: The elements of the matrix should be distinct i.e used only onceNumbers ranging from 1 to n^2Every sub-matrix you choose should have the sum of opposite corner elements as even i.e sum of top left and bott
6 min read
Python program to sort matrix based upon sum of rows
Given a Matrix, perform sort based upon the sum of rows. Input : test_list = [[4, 5], [2, 5, 7], [2, 1], [4, 6, 1]] Output : [[2, 1], [4, 5], [4, 6, 1], [2, 5, 7]] Explanation : 3 &lt; 9 &lt; 11 &lt; 14. Sorted sum. Input : test_list = [[4, 5], [2, 5, 7], [4, 6, 1]] Output : [[4, 5], [4, 6, 1], [2, 5, 7]] Explanation : 9 &lt; 11 &lt; 14. Sorted sum
6 min read
Python Program to find transpose of a matrix
Transpose of a matrix is obtained by changing rows to columns and columns to rows. In other words, transpose of A[][] is obtained by changing A[i][j] to A[j][i]. For Square Matrix: The below program finds transpose of A[][] and stores the result in B[][], we can change N for different dimension. C/C++ Code # Python3 Program to find # transpose of a
5 min read
Python Program to sort rows of a matrix by custom element count
Given Matrix, the following program shows how to sort rows of a matrix by the count of presence of numbers from a specified list. Input : test_list = [[4, 5, 1, 7], [6, 5], [9, 8, 2], [7, 1]], cus_list = [4, 5, 7] Output : [[9, 8, 2], [6, 5], [7, 1], [4, 5, 1, 7]] Explanation : 0 &lt; 1 = 1 &lt; 3 is order of custom elements count.Input : test_list
5 min read
Python Program to find the Next Nearest element in a Matrix
Given a matrix, a set of coordinates and an element, the task is to write a python program that can get the coordinates of the elements next occurrence. Input : test_list = [[4, 3, 1, 2, 3], [7, 5, 3, 6, 3], [8, 5, 3, 5, 3], [1, 2, 3, 4, 6]], i, j = 1, 3, K = 3 Output : (1, 4) Explanation : After (1, 3), 3 is found at (1, 4) Input : test_list = [[4
4 min read
Python program to search for the minimum element occurring consecutively n times in a matrix
Given a matrix containing n rows. Each row has an equal number of m elements. The task is to find elements that come consecutively n times horizontally, vertically, diagonally in the matrix. If there are multiple such elements then print the smallest element. If there is no such element then print -1.Examples: Input : n = 4 mat[5][5] 2 1 3 4 5 3 2
4 min read
Python Program to Convert Tuple Matrix to Tuple List
Given a Tuple Matrix, flatten to tuple list with each tuple representing each column. Example: Input : test_list = [[(4, 5), (7, 8)], [(10, 13), (18, 17)]] Output : [(4, 7, 10, 18), (5, 8, 13, 17)] Explanation : All column number elements contained together. Input : test_list = [[(4, 5)], [(10, 13)]] Output : [(4, 10), (5, 13)] Explanation : All co
8 min read
Python program to Convert Matrix to List of dictionaries
Given a Matrix, convert it to a list of dictionaries by mapping similar index values. Input : test_list = [["Gfg", [1, 2, 3]], ["best", [9, 10, 11]]] Output : [{'Gfg': 1, 'best': 9}, {'Gfg': 2, 'best': 10}, {'Gfg': 3, 'best': 11}] Input : test_list = [["Gfg", [1, 2, 3]]] Output : [{'Gfg': 1}, {'Gfg': 2}, {'Gfg': 3}] Method #1: The brute way in whic
4 min read
Python program to remove rows with duplicate element in Matrix
Given Matrix, remove all rows which have duplicate elements in them. Input : test_list = [[4, 3, 2], [7, 6, 7], [2, 4, 4], [8, 9, 9]] Output : [[4, 3, 2]] Explanation : [4, 3, 2] is the only unique row. Input : test_list = [[4, 3, 3, 2], [7, 6, 7], [2, 4, 4], [8, 9, 9]] Output : [] Explanation : No unique row. Method 1 : Using list comprehension +
5 min read
Python Program to Merge a Matrix By the Elements of First Column
Given a Matrix, perform merge on the basis of the element in the first column. Input : test_list = [[4, "geeks"], [3, "Gfg"], [4, "CS"], [4, "cs"], [3, "best"]] Output : [[4, 'geeks', 'CS', 'cs'], [3, 'Gfg', 'best']] Explanation : 4 is paired with geeks, CS and cs hence are merged into 1 row. Input : test_list = [[4, "geeks"], [3, "Gfg"], [4, "CS"]
5 min read
Python program to Sort Matrix by Maximum Row element
Given a Matrix, sort rows by maximum element. Input : test_list = [[5, 7, 8], [9, 10, 3], [10, 18, 3], [0, 3, 5]] Output : [[10, 18, 3], [9, 10, 3], [5, 7, 8], [0, 3, 5]] Explanation : 18, 10, 8 and 5 are maximum elements in rows, hence sorted. Input : test_list = [[9, 10, 3], [10, 18, 3], [0, 3, 5]] Output : [[10, 18, 3], [9, 10, 3], [0, 3, 5]] Ex
4 min read
Python Program that prints rows from the matrix that have same element at a given index
Given a Matrix, the following article shows how rows which has similar digit at the specified index will be extracted and returned as output. Input : test_list = [[3345, 6355, 83, 938], [323, 923, 845], [192, 993, 49], [98, 34, 23]], K = 1 Output : [[3345, 6355, 83, 938], [192, 993, 49]] Explanation : 3 and 9 [ same ] in 1st column.Input : test_lis
5 min read
Python Program that filters out non-empty rows of a matrix
Given Matrix, the following article shows how to filter all the Non-Empty rows of a matrix. In simpler terms, the codes provided below return a matrix after removing empty rows from it. Input : test_list = [[4, 5, 6, 7], [], [], [9, 8, 1], []] Output : [[4, 5, 6, 7], [9, 8, 1]] Explanation : All empty rows are removed.Input : test_list = [[4, 5, 6,
4 min read
three90RightbarBannerImg