Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

__add__ matrices method in python 2.7

I'm newbee in Python, so i need your help. Programm must add and substract 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'm adding 2 matrices it work great, but if i'm adding 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 do wrong. Please help me. Thank you!

like image 896
Shevko Avatar asked Aug 04 '26 03:08

Shevko


1 Answers

The problem is you're not returning a Matrix object but an actual matrix, i.e. a list of a lists. So when you concatenate 2 objects it's ok, but when you do it with 3 objects, you're actually trying to concatenate a list object with a Matrix object.

In other words, simply change the function to return a new instance, like so:

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 probably want to similarly change __sub__ as well.

like image 152
yuvi Avatar answered Aug 05 '26 18:08

yuvi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!