简体   繁体   中英

Matrices class with AssertionError

I am currently working with matrices and therefore created a Matrix Class. As this is part of a course, I was provided with a test.py file in order to check if my code is correct. Unfortunately I am receiving this error message:

   ---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-10-7d778e0a6ec7> in <module>()
     74     return True
     75 
---> 76 test()
     77 
     78 

<ipython-input-10-7d778e0a6ec7> in test()
     52 
     53     assert equal(-I2, I2_neg), "Error in your __neg__ function"
---> 54     assert equal(I2 + I2_neg, zero), "Error in your __add__ function"
     55     #assert equal(m1 * m2, m1_x_m2), "Error in your __mul__ function"
     56     #assert equal(m2 * m1, m2_x_m1), "Error in your __mul__ function"

AssertionError: Error in your __add__ function

The part I don't understand. If I comment one of the tests out eg

#assert equal(-I2, I2_neg), "Error in your __neg__ function"
assert equal(I2 + I2_neg, zero), "Error in your __add__ function"

Then it works. So it seems the problem only occurs when running both together.

My Matrix.py:

import math
from math import sqrt
import numbers

class Matrix(object):


    # Constructor
    def __init__(self, grid):
        self.g = grid
        self.h = len(grid)
        self.w = len(grid[0])

    #
    # Begin Operator Overloading
    ############################
    def __getitem__(self,idx):
        """
        Defines the behavior of using square brackets [] on instances
        of this class.

        Example:

        > my_matrix = Matrix([ [1, 2], [3, 4] ])
        > my_matrix[0]
          [1, 2]

        > my_matrix[0][0]
          1
        """
        return self.g[idx]

    def __repr__(self):
        """
        Defines the behavior of calling print on an instance of this class.
        """
        s = ""
        for row in self.g:
            s += " ".join(["{} ".format(x) for x in row])
            s += "\n"
        return s

    def __add__(self,other):
        """
        Defines the behavior of the + operator
        """
        if self.h != other.h or self.w != other.w:
            raise(ValueError, "Matrices can only be added if the dimensions are the same") 
        #   
        # TODO - your code here
        #

        matrix_addition = []
        for i in range(self.h):
            new_row = []
            for j in range(self.w):
                addition = self.g[i][j] + other.g[i][j]
                new_row.append(addition)

            matrix_addition.append(new_row)

        return Matrix(matrix_addition)


    def __neg__(self):
        """
        Defines the behavior of - operator (NOT subtraction)

        Example:

        > my_matrix = Matrix([ [1, 2], [3, 4] ])
        > negative  = -my_matrix
        > print(negative)
          -1.0  -2.0
          -3.0  -4.0
        """
        #   
        # TODO - your code here
        #
        for i in range(self.h):
            for j in range(self.w):
                self.g[i][j] *= -1   

        return Matrix(self.g)

    def __sub__(self, other):
        """
        Defines the behavior of - operator (as subtraction)
        """
        #   
        # TODO - your code here
        #

        if self.h != other.h or self.w != other.w:
            raise(ValueError, "Matrices can only be substracted if the dimensions are the same")

        matrix_substraction = []
        for i in range(self.h):
            new_row = []
            for j in range(self.w):
                addition = self.g[i][j] - other.g[i][j]
                new_row.append(addition)

            matrix_substraction.append(new_row)

        return Matrix(matrix_substraction)

Test.py

import matrix as m

def test():
    I2 = m.Matrix([
        [1, 0],
        [0, 1]
        ])
    I2_neg = m.Matrix([
        [-1, 0],
        [0, -1]
        ])

    zero = m.Matrix([
        [0,0],
        [0,0]
        ])

    assert equal(-I2, I2_neg), "Error in your __neg__ function"
    assert equal(I2 + I2_neg, zero), "Error in your __add__ function"

    print("Congratulations! All tests pass. Your Matrix class is working as expected.")

def equal(m1, m2):
    if len(m1.g) != len(m2.g): return False
    if len(m1.g[0]) != len(m2.g[0]): return False
    for r1, r2 in zip(m1.g, m2.g):
        for v1, v2 in zip(r1, r2):
            if abs(v1 - v2) > 0.0001:
                return False
    return True

test()

Anyone knows what's going wrong there?

Thanks a lot for your help! /Marc

In your __neg__ method, you are modifying your Matrix class in-place instead of returning a new one, you can print your variables in this order to see what's happening :

print I2, '\n'
print -I2, '\n'
print I2

It will output :

1  0 
0  1 


-1  0 
0  -1 


-1  0 
0  -1

You can solve it by creating a new Matrix object in your __neg__ method, and returning it, instead of modifying the one you already have, and returning it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM