我正在尝试使用简单的递归来计算矩阵的行列式(行主序),但是由于某种原因变量matrix在最后一个循环中发生了变化,我不明白为什么,因为我没有编写任何更改的代码变量的值。import mathdef print_m(matrix): # Print the matrix for i in range(len(matrix)): print(matrix[i])def determinant(matrix):# return determinant assuming scanning through first row if len(matrix[0]) != len(matrix): print('Not square matrix') return None if len(matrix) == 2: print('LAST STEP EXECUTED') return matrix[0][0]*matrix[1][1] - matrix[0][1]*matrix[1][0] def get_reduced_matrix(matrix, column): #not responsible for changin sign newM = matrix[1:] for i in range(len(matrix) - 1): del newM[i][column] return newM output = 0 for i in range(len(matrix)): #value of matrix changed when i turned into 1 print("i =", i) print_m(matrix) print('END') output += matrix[0][i] * determinant(get_reduced_matrix(matrix, i)) * math.pow(-1, i + 1) # change in sign at last print('Gonna do the loop again') return outputmatrix1 = [ [11, 12, 13], [21, 22, 23], [31, 32, 33]]print(determinant(matrix1))输出:C:\Users\jason\Desktop\Python\venv\Scripts\python.exe C:/Users/jason/.PyCharmCE2018.1/config/scratches/sdf.pyi = 0Traceback (most recent call last): File "C:/Users/jason/.PyCharmCE2018.1/config/scratches/sdf.py", line 38, in <module>[11, 12, 13] print(determinant(matrix1))[21, 22, 23][31, 32, 33] File "C:/Users/jason/.PyCharmCE2018.1/config/scratches/sdf.py", line 26, in determinantend output += matrix[0][i] * determinant(get_reduced_matrix(matrix, i)) * math.pow(-1, i + 1) # change in sign at lastLAST STEP EXECUTEDTypeError: unsupported operand type(s) for *: 'int' and 'NoneType' #MATRIX LOST SOME OF ITS VALUE HEREgonna do the loop againi = 1[11, 12, 13][22, 23][32, 33]endNot square matrixProcess finished with exit code 1所以矩阵刚刚失去了在第二和第三排的第一列条目,我不知道在所有的事了。就像我说的,我一开始并没有编写任何可以更改matrix值的代码。
1 回答
千巷猫影
TA贡献1829条经验 获得超7个赞
它改变的原因是因为矩阵包含对组成行的数组的引用。
如果你有一个矩阵:
matrix1 = [
[11, 12, 13],
[21, 22, 23],
[31, 32, 33]
]
然后你拿一块:
newM = matrix[1:]
newM 是一个新矩阵,但它包含对与原始矩阵相同的行数组的引用:
>> newM = matrix[1:]
>> newM[0] is matrix[1] # is it the same reference
True
如果您想在不更改原始行的情况下操作它们,则需要制作更深的行副本。也许是这样的:
newM = [m[:] for m in matrix[1:]]
在这种情况下会起作用吗?
添加回答
举报
0/150
提交
取消