__Add__ matrices method in python 2.7

I am new to Python, so I need your help. The program must add and subtract random matrices.

import random
class Matrix:
    def __init__(self):
        self.mat = [[]]
    def gen_ran_numb(self,row=5,col=5):
        self.mat=[[random.randint(0,10) for z in xrange(col)] for z in xrange(row)]
    def print_matrix(self):
        print self.mat
    def __add__(self,b):
        mat=[]
        for j in range(len(self.mat)):
            temp=[]            
            for k in range(len(self.mat[0])):
                x=self.mat[j][k] + b.mat[j][k]
                temp.append(x)
            mat.append(temp)
            rez=mat
        return rez
    def __sub__(self,b):
        mat=[]
        for j in range(len(self.mat)):
            temp=[]            
            for k in range(len(self.mat)):
                x=self.mat[j][k] - b.mat[j][k]
                temp.append(x)
            mat.append(temp)            
        return mat        

a=Matrix()
b=Matrix()
c=Matrix()
a.print_matrix()
a.gen_ran_numb(5,5)
b.gen_ran_numb(5,5)
c.gen_ran_numb(5,5)
a.print_matrix()
b.print_matrix()
c.print_matrix()
print b+a
print b+a+c

      

If I add 2 matrices it works fine, but if I add 3 or 4 matrices I took this error:

Traceback (most recent call last):
File "C:/Users//Documents/Python/task.py", line 40, in <module>
print b+a+c
TypeError: can only concatenate list (not "instance") to list

      

I don't understand what I am doing wrong. Please help me. Thank!

+3


source to share


1 answer


The problem is that you are not returning an object Matrix

, but an actual matrix, i.e. list of lists. So when you are concatenating 2 objects that is fine, but when you are doing it with 3 objects you are actually trying to concatenate the list object with the object Matrix

.

In other words, just change the function to return a new instance, like this:



def __add__(self, b):
    res = Matrix()
    res.mat = [] #to avoid an unwanted empty list at the beginning of new matrix
    for j in range(len(self.mat)):
        temp = []            
        for k in range(len(self.mat[j])):
            x = self.mat[j][k] + b.mat[j][k]
            temp.append(x)
        res.mat.append(temp)
    return res

      

You will probably want to change too __sub__

.

+4


source







All Articles