矩阵链应用程序中所有可能的分组

2024-05-23 18:58:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我研究了矩阵链乘法,其中给定一系列矩阵,目标是找到最有效的方法来乘法矩阵。问题实际上不是执行乘法,而只是决定所涉及的矩阵乘法的顺序。你知道吗

比如说。给定两个矩阵A和B,我可以有一个可能的矩阵组合,它是(AB),当我的矩阵是3:A, B, C,时,我可以有两个可能的组合:(AB)CA (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); 

如何修改上面的代码以适应我的问题?请帮忙。你知道吗


Tags: 代码pos目标closereturnifabdef