【发布时间】:2019-03-02 22:06:34
【问题描述】:
我研究过矩阵链乘法,其中给定一个矩阵序列,目标是找到最有效的矩阵乘法方法。问题实际上并不在于执行乘法,而只是决定所涉及的矩阵乘法的顺序。这就是为什么我的任务是编写一个程序,该程序在矩阵乘法中输出所有可能的矩阵组合,给定 n 作为输入矩阵的数量。例如
n == 1 (A)
n == 2 (AB)
n == 3 (AB)C , A(BC)
n== 4 ((AB)C)D, (A(BC))D, A((BC)D), A(B(CD)), (AB)(CD)
我的初始代码如下,由
调用 possible_groupings(4) #4 matrices
def possible_groupings(n):
print("Possible Groupings : ")
total = 0
if(n==1):
print('A')
total = total + 1
elif(n==2):
print('(AB)')
total = total + 1
else:
a = 2
while(a <= n-1):
b = 0
while((b+a) <= (n )):
c = b
d = 0
substr = ''
while (d < c):
substr = substr + chr(65 + d)
d = d + 1
if substr != '':
if len(substr) == 1:
print( substr, end = '')
else:
print('(' + substr + ')', end = '')
print('(', end = '')
while (c < (b +a)):
print(chr(65 + c), end = '');
c = c + 1
print(')', end = '')
e = b+a
substr = ''
while (e < n):
substr = substr + chr(65 + e)
e = e + 1
if substr != '':
if len(substr) == 1:
print( substr, end = '')
else:
print('(' + substr + ')', end = '')
print('')
total = total + 1
b = b + 1
a = a + 1
print('Total : ' + str(total))
当我的inout是4个矩阵时,上面代码的输出是:
(AB)(CD)
A(BC)D
(AB)(CD)
(ABC)D
A(BCD)
如何修改我的代码。矩阵的数量必须在 1-26 范围内。我现在头很痛。请帮忙。
【问题讨论】:
-
你能更详细地解释一下你想要什么样的输出。说
n==3,它说你希望你的输出是(AB)C , A(BC)。这到底是什么意思? AB和BC?那么ABC、A、B和C呢?我想我不明白你的符号。 -
@Joe --> 我在做矩阵链乘法,我必须尝试所有可能的矩阵组合。这就是为什么我们需要输出矩阵的所有可能组合或优先乘法。
-
哦,我现在明白了。让我考虑一下。
-
你知道矩阵乘法顺序问题的动态规划方法吗? (是的,生成可能的括号组合也是一项非常有趣的任务)
-
所以我想您知道不需要生成所有变体,但希望将它们作为参考或很好的练习。
标签: python python-3.x algorithm math matrix