这是为其编写 unittest 的函数:
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]
"""
这是单元测试代码:
def test_swap_k_list_length_6_swap_2(self):
"""Test swap_k with list of length 6 and number of items to swap 2.
Also allow for the fact that there are potentially four alternate
valid outcomes.
"""
list_original = [1, 2, 3, 4, 5, 6]
list_outcome_1 = [5, 6, 3, 4, 1, 2]
list_outcome_2 = [5, 6, 3, 4, 2, 1]
list_outcome_3 = [6, 5, 3, 4, 1, 2]
list_outcome_4 = [6, 5, 3, 4, 2, 1]
valid_outcomes = [list_outcome_1, list_outcome_2, list_outcome_3, list_outcome_4]
k = 2
a1.swap_k(list_original,k)
self.assertIn(list_original, valid_outcomes)
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
unittest 代码通过了,我不明白为什么,因为我认为唯一有效的结果是 list_outcome_1 从 swap_k 的文档字符串判断...