Skip to content
Advertisement

Question regarding a matrix class function

First, here is my code:

class matrix:
def __init__(self, m, n): 
    self._m, self._n = m, n

    L = []  # We first define our pre-matrix as an empty list
    for i in range(m):  
        L.append(0)

    for j in range(m):  
        L[j] = [0] * n

    self._matrix = L 


def __setitem__(self, c, value):
    self._matrix[c[0] - 1][c[1] - 1] = value

def __str__(self):
    l = ""  
    for i in range(self._m):
        l = l + " "  
        for j in range(self._n):
            l = l + str(self._matrix[i][j]) + " "  
        l = l + " n"  
    return l


def __add__(self, other):
    result = [[self._matrix[i][j] + other._matrix[i][j] for j in range(len(self._matrix[0]))] for i in range(len(self._matrix))]
    return result

When adding two (non-zero) matrices I can not make the result be printed nicely as my __str__ method would do, instead of having

a b c 
d e f

I get the usual,

[[a, b, c],[d, e, f]]

Does anyone have an idea on how to fix the issue?

Advertisement

Answer

The return type of add function is a list. It should be a matrix.

def __add__(self, other):
    result = matrix(self._m, self._n)
    result._matrix = [[self._matrix[i][j] + other._matrix[i][j] for j in range(len(self._matrix[0]))] for i in range(len(self._matrix))]
    return result 
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement