The following code in Python 3 is meant to return the determinant of any order matrix. It takes in a text file with the form :
3 6 8 9
9 -7 5 -7
2 0 8 0
8 9 -1 -1
I get no error, but it is giving the wrong answer. Any clue why? Thanks!
def determinant(inputFileName):
def cofactorExp(listOfRows):
if len(listOfRows) <= 2:
return (float(listOfRows[0][0]) * float(listOfRows[1][1])) - (float(listOfRows[0][1]) * float(listOfRows[1][0]))
else:
for i in range(len(listOfRows)):
tempList = listOfRows[:]
del tempList[i]
for x in range(len(tempList)):
tempList[x] = tempList[x][1:]
det = ((-1) ** i) * float(listOfRows[i][0]) * cofactorExp(tempList)
return det
rows = []
for line in open(inputFileName):
rows append(line split(" "))
for item in rows:
if "\n" in item[len(item) - 1]:
item[len(item) - 1] = item[len(item) - 1][:-1]
return(cofactorExp(rows))