我正在嘗試使用簡單的遞歸來計算矩陣的行列式(行主序),但是由于某種原因變量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
提交
取消