-2

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))  
starrify
  • 14,307
  • 5
  • 33
  • 50
  • You can use numpy for this task, unless this is a homework assignment: http://stackoverflow.com/questions/462500/can-i-get-the-matrix-determinant-by-numpy – Anderson Green Nov 25 '13 at 05:50
  • 1
    Work it out by hand and see where your function's calculations start to differ. – Blender Nov 25 '13 at 06:16
  • It's a homework assignment, but we were allowed to make code that does what we want. I can't use that though. – user3029811 Nov 25 '13 at 06:21

2 Answers2

0

A few things

Your open file command doesnt properly handle spaces before and after the data

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]

when I ran the code on my made up matrix, the command return this

[['3', '6', '8', '9'], ['9', '-7', '5', '-7'], ['2', '0', '8', '0'], ['8', '9', '-1', '-1', '']]

Notice there is an empty element in the matrix. Dont forget to add periods when calling a command in an object

I recommend using the example for csv module http://docs.python.org/2/library/csv.html

return det

seems to prematurely exit the function since the det is in the scope of the loop

Lastly, there is an easier method to solve and code the determinant

   (aei+bfg+cdh)-(ceg+bdi+afh) 

http://en.wikipedia.org/wiki/Determinant

user1462442
  • 7,672
  • 1
  • 24
  • 27
0
from numpy import *
x=input("give order of square matrix")
a=[]
for i in range(x):
    a.append([])
    for j in range(x):
        y=raw_input("input a["+str(i)+"]["+ str(j)+ "] element")
        a[i].append(y)
b=array(a)


print b

def rem(cc):
    s=cc.shape
    y=[]
    for i in range(s[0]):
        y.append([])
        for j in range(s[0]):
            if i==0:
                continue
            elif j==x:
                continue
            else:
                y[i].append(cc[i][j])
    y.pop(0)          
    return array(y)

def det(bb):
    n=0
    s=bb.shape  
    if s==(1,1):
        return bb[0][0]
    else:
        for j in range(s[0]):
            x=j
            global x  
            p=int(bb[0][j])
            pp=int(det(rem(bb)))        
            k=p*pp
            n=n+((-1)**(j))*int(k)
    return n

print "value is ",det(b)
psxls
  • 6,807
  • 6
  • 30
  • 50
  • You should provide some info on what this code is all about, and how it might help answer the question! – psxls Dec 13 '13 at 12:32