我正在尝试使用简单的递归来计算矩阵的行列式(行主序),但是由于某种原因变量matrix在最后一个循环中发生了变化,我不明白为什么,因为我没有编写任何更改的代码变量的值。
import math
def 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 output
matrix1 = [
[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.py
i = 0
Traceback (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 determinant
end
output += matrix[0][i] * determinant(get_reduced_matrix(matrix, i)) * math.pow(-1, i + 1) # change in sign at last
LAST STEP EXECUTED
TypeError: unsupported operand type(s) for *: 'int' and 'NoneType' #MATRIX LOST SOME OF ITS VALUE HERE
gonna do the loop again
i = 1
[11, 12, 13]
[22, 23]
[32, 33]
end
Not square matrix
Process finished with exit code 1
所以矩阵刚刚失去了在第二和第三排的第一列条目,我不知道在所有的事了。就像我说的,我一开始并没有编写任何可以更改matrix值的代码。
千巷猫影
相关分类