问题是要修复故意不正确的代码,以便可以执行 pyUnit 测试。代码中的错误将使用测试找到,然后更正。我的上次测试在代码中产生了一个错误,但我无法发现它!
给定的代码(有错误)
def linear( target, list ):
""" returns the position of target,
if not found returns -1"""
position = 0
if len(list)==0:
return -1
else:
while position <= (len(list)+1):
if target == list[position]:
return position
position += 1
return -1
和我的测试:
import unittest
# import the module(s) to be tested:
from LinearSearch import *
class TestLinearSearch(unittest.TestCase):
# setUp - run prior to the start of each test case
def setUp(self):
# initialize test fixtures
return
def test_smoke(self):
# very simple test to insure test framework is correct
self.assertTrue(1)
# additional test_xxx methods follow....
def test_emptyList(self):
self.assertEqual(linear(4,[]),-1)
def test_singleChar(self):
self.assertEqual(linear(1,[1]),0)
def test_isInList(self):
self.assertEqual(linear(4,[1,2,3,4,5]),3)
def test_isNotInList(self):
self.assertEqual(linear(8,[1,2,3,4,5]),-1)
if __name__ == '__main__':
unittest.main()
产生我的错误的测试是最后一个测试:“test_isNotInList(self)”,它是一个索引越界错误...应该很简单,但我只需要一点帮助。
最佳答案
在您上次的测试中,该函数访问了超出范围的 list[5]
。这会导致 IndexError
。您可以在不引发异常的情况下访问的最大索引比列表的长度少一个。您可以通过修改 while
循环的条件来解决此问题:
while position < len(list):
或者更好的是,直接遍历列表,使用 enumerate
确定位置:
def linear( target, list ):
""" returns the position of target,
if not found returns -1"""
for idx, element in enumerate(list):
if element == target:
return idx
return -1
关于python - 简单的线性搜索测试(python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18835663/