带有AssertionError的矩阵类

时间:2018-01-11 09:36:08

标签: python

我目前正在使用矩阵,因此创建了一个Matrix类。由于这是课程的一部分,我获得了一个test.py文件,以检查我的代码是否正确。不幸的是,我收到此错误消息:

   ---------------------------------------------------------------------------
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

我不明白的部分。如果我评论其中一个测试,例如

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

然后它有效。因此,只有在一起运行时才会出现问题。

我的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()

有人知道那里出了什么问题吗?

非常感谢你的帮助! /马克

1 个答案:

答案 0 :(得分:0)

__neg__方法中,您正在修改Matrix课程,而不是返回新课程,您可以按此顺序打印变量以查看发生了什么:< / p>

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

将输出:

1  0 
0  1 


-1  0 
0  -1 


-1  0 
0  -1

您可以通过在Matrix方法中创建新的__neg__对象并将其返回,而不是修改已有的对象并将其返回来解决此问题。