Question

The problem is to fix intentionally incorrect code so that pyUnit tests can be preformed. The error(s) in the code are to be found using the tests, then corrected. My last test generates an error in the code, but I cant spot it!

given code(w/ errors)

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

and my tests:

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

the test that generates my error is the last test: "test_isNotInList(self)", it is an index out of bounds error...should be simple enough but I just need a little help.

Was it helpful?

Solution

In your last test, the function accesses list[5], which is out of range. This causes an IndexError. The largest index you can access without raising an exception is one less than the length of the list. You can address this by modifying the condition of your while loop:

while position < len(list):

Or even better, just iterate through the list directly, determining the position using 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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top