0

I am trying to make a program to find the determinant of an N*N matrix and here is my code:

from copy import deepcopy

n = input()
myMatrix = []

for i in range(n):
    myMatrix.append(raw_input().split())

def findMinor(matrix, i):
    minor = deepcopy(matrix)
    del minor[0]
    for b in range(len(matrix)-1):
        del minor[b][i]
    return minor

def det(matrix):
    determinant = 0
    if len(matrix) == 1:
        determinant = matrix[0][0]
    else:
        for x in range(len(matrix)):
            coFactor = det(findMinor(matrix,x))
            determinant += int(matrix[0][x]) * (-1)**(2+x) * coFactor
            return determinant

print det(myMatrix)

I am getting No-Type error and I'm pretty sure its because I'm calling a function within itself since it is a recursive approach.

Is there any way to fix this? Possibly even dump the second function?

Mehdi Alali
  • 163
  • 1
  • 11

1 Answers1

1

Your problem is that det only returns something in the else part of the if.. else

If len(matrix)==1, nothing happens (or at least nothing is returned). So when n=2 it tries to use cofactor which should be the result from an n=1 calculation, the value of cofactor is None.

so remove the indentation before return determinant so it's out of the if.. else.. part of the code.

Even after fixing this, you'll have other problems. You'd be better off storing your matrix as a lot of floats rather than strings. If you want to leave it as strings, make determinant=int(matrix[0][0])

I think the best way to fix the string issue is:

for i in range(n):
    myMatrix.append(map(float,raw_input().split()))

And for what it's worth, if you want to really do matrix calculations, don't use your own data structures. Use numpy - it will be faster than anyone could write in pure python.

Joel
  • 22,598
  • 6
  • 69
  • 93