sum() python built in function, are there any alternatives?

Viewed 46

I'm trying to create a python module for linear algebra that includes the classes Matrix and Vector. I had the idea to include the cross product, and wanted to implement it following the definition (the determinant of the mixed matrix containing in the first column the canonical basis and in the other columns the coordinates of the vectors in that basis).

I have already a method for the determinant in the class SqMatrix (subclass of Matrix) and it works quite well on normal matrices. Here's the code:

class Matrix:
 def__init__(self,L):
  self.grid=[i[:] for i in L]
  self.rows=len(L)
  self.columns=len(L[0])

class SqMatrix(Matrix):
 def __init__(self,L):
  Matrix.__init__(self,L)
 def extract(self,i,j):
  return SqMatrix([[self.grid[ii][jj] for jj in range(self.rows) if jj!=j] for ii in range(self.rows) if ii!=i])
 def det(self):
  if self.rows==1:
   return self.grid[0][0]
  return sum([(-1)**i*self.grid[i][0]*self.extract(i,0).det() for i in range(self.rows)])
  

The problem is that plugging in vectors in the list contained in the sum() raises an error because sum() only accepts lists with numerical values.

If it's helpful I'll include also the actual code that raises the error:

class Vector: # I didn't define the class in the previous sample because it didn't matter
 def __init__(self,L):
  self.values=L[:]
 def __add__(self,other): #I'm not including the checks I had in the program, other should be a vector of the same length
  return Vector([self.values[i]+other.values[i] for i in range(len(self.values))]) 
 def __rmul__(self,other): #to implement the product by the scalars
  return Vector([other*self.values[i] for i in range(len(self.values))])

A=SqMatrix([[1,Vector([1,0])],[0,Vector([0,1])]])#the matrix shold have the vectors in the first column, but this changes only the sign so i'm happy with it
A.det()

The idea was that for each sub-determinant i would get a vector and then I could sum all the results together, but I don't know a function other than sum() that does that. The Error that arises is:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "Desktop\python\LinearAlgebra.py", line 343, in det
    return sum([((-1)**i)*self.grid[i][0]*self.extract(i,0).det() for i in range(self.rows)])
TypeError: unsupported operand type(s) for +: 'int' and 'instance'

Any hints on how to tackle the problem?

0 Answers
Related