【发布时间】:2018-09-26 15:29:53
【问题描述】:
我研究过矩阵链乘法,其中给定一个矩阵序列,目标是找到最有效的矩阵乘法方法。问题实际上并不在于执行乘法,而只是决定所涉及的矩阵乘法的顺序。
比如说。给定 2 个矩阵 A 和 B,我可以有一个可能的矩阵组合,即 (AB),当我的矩阵是 3 时:A, B, C, 我可以有两种可能的组合:(AB)C 和 A (BC)。我想实现一个代码,因为矩阵的数量将在 Python 中输出所有可能的矩阵组合。
下面的代码不正确,因为给定 n = 3 个矩阵,它输出 5 个组合,而实际上它应该只有 2 个。下面的代码正在打印平衡括号的所有组合。
def printParenthesis(str, n):
if(n > 0):
_printParenthesis(str, 0,
n, 0, 0,0);
return;
def _printParenthesis(str, pos, n,
open, close, count):
if(close == n):
for i in str:
print(i, end = "");
print();
return;
else:
if(open > close):
str[pos] = '}';
_printParenthesis(str, pos + 1, n,
open, close + 1, count);
if(open < n):
str[pos] = '{' + chr(65+count);
_printParenthesis(str, pos + 1, n,
open + 1, close, count+1);
# Driver Code
n = 3; //Number of matrices
str = [""] * 2 * n;
printParenthesis(str, n);
我将如何修改上面的代码以适应我的问题?请帮忙。
【问题讨论】:
标签: python matrix matrix-multiplication