How do I determine a square matrix in python?

Asked

Viewed 3,879 times

0

My file is like this:

arq = open('matriz.txt', 'r')  
texto = []  
matriz = [] 
texto = arq.readlines() 


for i in range(len(texto)):         
    matriz.append(texto[i].split())  


for i in range(len(texto)):         
    print(matriz[i])  


arq.close() 
  • Could post the contents of the input file matriz.txt also ?

  • would be a file like this 10#10#10

1 answer

1

You can use the package NumPy, who owns a wide collection of functions mathematics capable of working with multidimensional matrices.

To compute the determinant of a matrix you can use the function numpy.linalg.det(), look at you:

import numpy

matriz = [ [1, 1, 1], [2, 2, 2], [3, 3, 3] ]

print( numpy.linalg.det( matriz ) )

See working on Repl.it

To read the matrix from a file and calculate its determinant:

import numpy

matriz = []

with open('matriz.txt', 'r')  as f:
    for linha in f.readlines():
      matriz.append( [ float(i) for i in linha.split() ] )

determ = numpy.linalg.det( matriz )

print(matriz)
print(determ) 

See working on Repl.it.

Or, simply:

import numpy

with open('matriz.txt', 'r')  as f:
    matriz = [[ float(i) for i in linha.split()] for linha in f.readlines()]

determ = numpy.linalg.det( matriz )

print(matriz)
print(determ)

See working on Repl.it.

  • I can’t use the numpy unfortunately.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.