import numpy as np def MatrixChain(p,n): #存储最优值 m = np.zeros((n+1,n+1)) # 牺牲第0行,第0列 s = np.zeros((n+1,n+1)) # 牺牲第0行,第0列 # 单个矩阵连乘的次数 for i in range(n+1): #对角线值为0 m[i][i] = 0; s[i][i] = 0; # r表示子问题的规模,即连乘的矩阵个数,从两个矩阵开始,规模逐步放大到n for r in range(2,n+1): for i in range(1,n-r+2): j =i+r-1 # 当前的子问题 m[i][j] =m[i+1][j]+p[i-1]*p[i]*p[j] s[i][j] =i for k in range(i+1,j): t = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j] if t<m[i][j]: m[i][j] = t s[i][j] = k return m,s # 备忘录 def Traceback(i,j,s): global res # 全局变量 if i == j: res.append('A'+ str(i)) else: res.append('(') Traceback(i,int(s[i][j]),s) Traceback(int(s[i][j])+1,j,s) res.append(')') if __name__ == '__main__': arr = [] for i in range(5): row = input(f"请输入第{i + 1}行,用空格分隔每个元素:") arr.append(row.split(" ")) n = int(len(arr)) res = [] # 处理矩阵的行和列 p = [] for i in range(n): if i==0: p.append(arr[0][0]) p.append(arr[0][1]) else: p.append(arr[i][1]) m,s = MatrixChain(p,n) Traceback(1,n,s) print(''.join(res))修改这段代码
时间: 2024-01-21 12:04:19 浏览: 92
cs231n课堂笔记翻译pdf版本(python-numpy)
以下是修改后的代码,主要是将输入方式改为了直接输入数字,同时纠正了一些语法错误:
```python
import numpy as np
def MatrixChain(p, n):
# 存储最优值
m = np.zeros((n+1, n+1)) # 牺牲第0行,第0列
s = np.zeros((n+1, n+1)) # 牺牲第0行,第0列
# 单个矩阵连乘的次数
for i in range(n+1): # 对角线值为0
m[i][i] = 0
s[i][i] = 0
# r表示子问题的规模,即连乘的矩阵个数,从两个矩阵开始,规模逐步放大到n
for r in range(2, n+1):
for i in range(1, n-r+2):
j = i+r-1 # 当前的子问题
m[i][j] = m[i+1][j] + p[i-1]*p[i]*p[j]
s[i][j] = i
for k in range(i+1, j):
t = m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j]
if t < m[i][j]:
m[i][j] = t
s[i][j] = k
return m, s
# 备忘录
def Traceback(i, j, s):
global res # 全局变量
if i == j:
res.append('A'+str(i))
else:
res.append('(')
Traceback(i, int(s[i][j]), s)
Traceback(int(s[i][j])+1, j, s)
res.append(')')
if __name__ == '__main__':
arr = []
for i in range(5):
row = input(f"请输入第{i+1}行,用空格分隔每个元素:")
arr.append(list(map(int, row.split())))
n = len(arr)
res = []
# 处理矩阵的行和列
p = []
for i in range(n):
if i == 0:
p.append(arr[0][0])
p.append(arr[0][1])
else:
p.append(arr[i][1])
m, s = MatrixChain(p, n)
Traceback(1, n, s)
print(''.join(res))
```
阅读全文