我试图编写一个可以对矩阵进行基本行操作的代码,但我遇到了一些问题。我意识到有些库具有可用于完成这些操作的功能;但是,我这样做是为了我自己的满足感。
更换操作出现问题。此操作的预期目的是将行的总和替换为另一行的倍数。例如,如果我有一个矩阵[[1,2,3],[2,1,3],[3,2,1]],我想替换顶行(行[1,2,3] ])用自身和第二行(行[2,1,3])乘以系数2.我希望代码能给我:[[5,4,9],[2, 1,3],[3,2,1]]
当我输入这个特定的矩阵时,得到的答案是:[[5,4,9],[4,2,6],[3,2,1]]
我的代码如下:
def multiply_row(matrix,row_num,factor):
#Let row_num = 1 indicate the top row
temp_row = matrix[row_num - 1]
entries = len(matrix[row_num - 1])
current_term = 0
while current_term < entries:
temp_row[current_term] = temp_row[current_term] * factor
current_term = current_term + 1
return temp_row
def replacement(matrix,rowA,rowB,factor):
#Replace 1 row be by the sum of itself and a multiple of another row
#rowA is the row being replaced
#rowB is being multiplied by the factor
#Let rowA = 1 indicate the top row
temp_rowB = multiply_row(matrix,rowB,factor)
entries = len(matrix[rowA - 1])
current_term = 0
while current_term < entries:
matrix[rowA - 1][current_term] = temp_rowB[current_term] + matrix[rowA - 1][current_term]
current_term = current_term + 1
return matrix
m = [
[1,2,3],
[2,1,3],
[3,2,1]
]
print replacement(m, 1, 2, 2)
显然,问题出在我的“multiply_row”函数中。我创建了这个函数,这样我就可以创建一个临时的位置,我可以将一个行乘以一个因子,而不会实际影响矩阵本身的行。这不起作用。
我想知道是否有人可以解释为什么这个临时行实际上正在改变矩阵本身的行。此外,我意识到我可能没有以最有效的方式进行操作,我很想知道更有效的方法是什么(这只是次要的,我真的很感激我的第一个回答问题)。
感谢您的帮助
答案 0 :(得分:1)
问题是temp_row
不是矩阵中行的副本,而是引用。因此,您对temp_row
所做的任何事情都会发生在矩阵中的相应行中,因为它发生在同一个对象上(恰好以两种不同的方式引用)。将multiply_row()
中的行替换为
temp_row = matrix[row_num - 1][:]
制作副本。然后你得到:
[[5, 4, 9], [2, 1, 3], [3, 2, 1]]
根据您的要求。