Welcome, guest | Sign In | My Account | Store | Cart

A small snipet of code to find the determinant of a mtrix of any order.Input must be a list like [[1,2,3],[4,5,6],[7,8,9]] (for a matrix of order 3). Works fine.

Python, 26 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
def det(l):
    n=len(l)
    if (n>2):
        i=1
        t=0
        sum=0
        while t<=n-1:
            d={}
            t1=1
            while t1<=n-1:
                m=0
                d[t1]=[]
                while m<=n-1:
                    if (m==t):
                        u=0
                    else:
                        d[t1].append(l[t1][m])
                    m+=1
                t1+=1
            l1=[d[x] for x in d]
            sum=sum+i*(l[0][t])*(det(l1))
            i=i*(-1)
            t+=1
        return sum
    else:
        return (l[0][0]*l[1][1]-l[0][1]*l[1][0])

Uses a recursive algorithm, the end point being solving a matrix of order 2 using simple formula. Will help in solving linear equations using crammers rule, or for other applications in higher linear algebra.

2 comments

zhr.3041 11 years, 2 months ago  # | flag

hi. tq for ur usefull program. by the way i cant understand whats d={} mean n also line 18 l1=[d[x] for x in d] whats that mean? em not familiar wid python yet. plz help me in this way

thank u so much

Sachin Joglekar (author) 11 years, 2 months ago  # | flag

@zhr.3041, d= {} initialises an empty dictionary. A dictionary is a mapping from keys to values, for eg, d= {1:"a', 2: 'b'}

l1 = [d[x] for x in d] this line creates a list with all the values of all the keys in d (only the values are stored, not the keys).