Hw:Python 测试采用两个参数计算它们的函数时出错 returns 一个列表

Hw: Python error when testing a function which takes two parameters computes them and returns a list

我创建了一个函数,它接受两个参数来计算它们,returns 一个列表,每个元素设置为参数 n 和输入列表中相应值的总和。这是我的函数代码:

    def add_n_all(L,n):
        listx = map(lambda x:x + n, L)
        return listx

测试我的功能的代码如下所示:

    def testmap_1(self):
        L = [2, 3, 4]
        n = 2
        L2 = map.add_n_all(L,n)
        self.assertListAlmostEqual(L2, [4, 2, 5, 3, 6, 4])

    def testmap_1(self):
        L = [2, 3, 4]
        n = 2
        L2 = map.add_n_all(L,n)
        self.assertListAlmostEqual(L2, [3, 1, 6, 4, 8, 6])

然而,当我 运行 我的测试时,我不断收到此错误。我试图改变周围的变量,但它似乎不起作用,所以我不确定我做错了什么。

失败:testmap_1(main.TestCases)

     Traceback (most recent call last):
        File "map_tests.py", line 33, in testmap_1
        self.assertListAlmostEqual(L2, [3, 1, 6, 4, 8, 6])
     File "map_tests.py", line 7, in assertListAlmostEqual
        self.assertEqual(len(l1), len(l2))
     AssertionError: 3 != 6

   Ran 3 tests in 0.001s

   FAILED (failures=1)

您的函数没有增加长度,因此您将一个包含 3 个元素的列表 (L2) 与一个包含 6 个元素的列表进行比较,这显然不相等。

However when I run my test I keep getting this error.

AssertionError in Python is raised when a test (or in other words an assert 失败。

在您的 assertListAlmostEqual 中检查输入和输出列表的长度。

 self.assertEqual(len(l1), len(l2))

在你的测试用例中输入

L = [2, 3, 4]

长度为 3。

map() 函数的输出列表的长度将与其输入的长度相同。因此,将输出 L2(即 3)的长度与 [3, 1, 6, 4, 8, 6](即 6)的长度进行比较显然会使断言失败。

因此,在您的测试用例中,您需要纠正与 L2 进行比较的内容。

改变

self.assertListAlmostEqual(L2, [3, 1, 6, 4, 8, 6])

self.assertListAlmostEqual(L2, [4, 5, 6])

通过测试(除非您打算测试负面情况,在这种情况下您需要使用 assertNotEqual)。

如果您的目的是获得一个输出列表 +n 每个元素以及列表中的相应元素,那么您可以执行以下操作之一(不编写代码。 ..这是你的硬件 rt...):

def add_n_all(L,n):
    # Consturct an empty list, which will be used to return as the output of this function
    # for each element in the list
        # do .extend() with [element+n, element] on the list initialized earlier for the purpose of this function return

    # return the output list

def add_n_all(L,n):
    # good luck figuring out this list comprehension
    return [item for sublist in [[x+n, x] for x in L] for item in sublist]