GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — algorithms/dp/matrix_chain_order.py at master · marcosfede/algorithms

Expand file tree

/

matrix_chain_order.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
51 lines (40 loc) · 1.44 KB
/

matrix_chain_order.py

Copy path

File metadata and controls

51 lines (40 loc) · 1.44 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
'''
Dynamic Programming
Implementation of matrix Chain Multiplication
Time Complexity: O(n^3)
Space Complexity: O(n^2)
'''
INF = float("inf")
def matrix_chain_order(array):
N = len(array)
matrix = [[0 for x in range(N)] for x in range(N)]
sol = [[0 for x in range(N)] for x in range(N)]
for chain_length in range(2, N):
for a in range(1, N - chain_length + 1):
b = a + chain_length - 1
matrix[a][b] = INF
for c in range(a, b):
cost = matrix[a][c] + matrix[c + 1][b] + array[a - 1] * array[c] * array[b]
if cost < matrix[a][b]:
matrix[a][b] = cost
sol[a][b] = c
return matrix, sol
# Print order of matrix with Ai as matrix
def print_optimal_solution(optimal_solution, i, j):
if i == j:
print("A" + str(i), end=" ")
else:
print("(", end=" ")
print_optimal_solution(optimal_solution, i, optimal_solution[i][j])
print_optimal_solution(optimal_solution, optimal_solution[i][j] + 1, j)
print(")", end=" ")
def main():
array = [30, 35, 15, 5, 10, 20, 25]
n = len(array)
# Size of matrix created from above array will be
# 30*35 35*15 15*5 5*10 10*20 20*25
matrix, optimal_solution = matrix_chain_order(array)
print("No. of Operation required: " + str((matrix[1][n - 1])))
print_optimal_solution(optimal_solution, 1, n - 1)
if __name__ == '__main__':
main()
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.