ここのユニットテストで NameError の問題を大量に検索しましたが、私の問題に関連するものは何も見つからないようです。
これは宿題のためなので、どこが間違っているのか教えていただければ、それを修正する方法は教えていただけないでしょうか. リストの最後の数字をリストの最初の数字と交換する関数の単体テストを作成しようとしています。
関数用に作成したコードは次のとおりです。
def swap_k(L, k):
""" (list, int) -> NoneType
Precondtion: 0 <= k <= len(L) // 2
Swap the first k items of L with the last k items of L.
>>> nums = [1, 2, 3, 4, 5, 6]
>>> swap_k(nums, 2)
>>> nums
[5, 6, 3, 4, 1, 2]
>>> nums = [1, 2, 3, 4, 5, 6]
>>> swap_k(nums, 3)
>>> nums
[4, 5, 6, 1, 2, 3]
"""
L[:k], L[-k:] = L[-k:], L[:k]
このコードは doctest を使用して正常に動作し、エラーはまったくないため、何も問題はないと確信しています。ただし、単体テスト用に記述したコードでは、NameError が発生し続けます。単体テストのコードは次のとおりです。
import a1
import unittest
class TestSwapK(unittest.TestCase):
""" Test class for function a1.swap_k. """
def test_swapk_1(self):
"""Swap the first k items of L with the last k items of L. Where L =
[1, 2, 3, 4, 5, 6] and k = 2."""
L = [1, 2, 3, 4, 5, 6]
expected = [5, 6, 3, 4, 1, 2]
a1.swap_k(L, k)
self.assertEqual(L, expected)
if __name__ == '__main__':
unittest.main(exit=False)
そして、これはエラーメッセージです:
E
======================================================================
ERROR: test_swapk_1 (__main__.TestSwapK)
Swap the first k items of L with the last k items of L. Where L =
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\xxxxx\xxxxxxxxxx\xxxxxxxxxxxx\test_swap_k.py", line 13, in test_swapk_1
a1.swap_k(L, k)
NameError: global name 'k' is not defined
----------------------------------------------------------------------
Ran 1 test in 0.016s
FAILED (errors=1)`
どこが間違っているのか誰か教えてください。繰り返しますが、答えを教えずにどこが間違っているかを教えていただける場合は、そうしてください。