ThomasNicholas - 8 months ago 52

Python Question

I'm trying to write a program to find the determinant of an NxN matrix in Python 3.3 but it returns a "list index out of range" error. There is a debugging print statement in the det function which shows that in the case of the 2 x 2 matrix example given then it works fine for the first minor, but then A is reduced to [[3]] and I can't see what part of my code is changing it at all? I want the det function to leave A unchanged as it works along the first row.

`def minor(matrix,i):`

"""Returns the Minor M_0i of matrix"""

minor = matrix

del minor[0] #Delete first row

for b in list(range(len(matrix))): #Delete column i

del minor[b][i]

return minor

def det(A):

"""Recursive function to find determinant"""

if len(A) == 1: #Base case on which recursion ends

return A[0][0]

else:

determinant = 0

for x in list(range(len(A))): #Iterates along first row finding cofactors

print("A:", A)

determinant += A[0][x] * (-1)**(2+x) * det(minor(A,x)) #Adds successive elements times their cofactors

print("determinant:", determinant)

return determinant

data = [[4, 3], [6, 3]]

print(det(data))

Answer

When you do `minor = matrix`

you aren't creating a copy of the matrix, you're just creating a new reference to it. When you next delete a row from `minor`

you're also deleting the row from `matrix`

.

`copy.deepcopy`

will probably do what you need.