简体   繁体   中英

Why isn't my Python code for finding determinants working?

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))  

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM