Searching Algorithms:
Linear Search with unittesting
import unittest
def linear_search(arr, target):
"""Performs a linear search on a list.
Args:
arr: The list to search.
target: The element to search for.
Returns:
The index of the target element if found, otherwise -1.
"""
for i in range(len(arr)):
if arr[i] == target:
return i
return -1
class TestLinearSearch(unittest.TestCase):
def test_found(self):
arr = [1, 2, 3, 4, 5]
target = 3
expected_index = 2
self.assertEqual(linear_search(arr, target), expected_index)
def test_not_found(self):
arr = [1, 2, 3, 4, 5]
target = 6
expected_index = -1
self.assertEqual(linear_search(arr, target), expected_index)
def test_empty_list(self):
arr = []
target = 5
expected_index = -1
self.assertEqual(linear_search(arr, target), expected_index)
def test_multiple_occurrences(self):
arr = [1, 2, 3, 3, 4, 5]
target = 3
expected_index = 2 # We return the first occurrence
self.assertEqual(linear_search(arr, target), expected_index)
if __name__ == '__main__':
unittest.main()
linear_searchfunction:- This function implements the linear search algorithm.
- It iterates through the list
arrand returns the index of the target element if found, otherwise -1.
TestLinearSearchclass:- This class inherits from
unittest.TestCaseand contains test methods for different scenarios of thelinear_searchfunction.
- This class inherits from
- Test Methods:
test_found: Checks if the function correctly finds the target element when it’s present in the list.test_not_found: Checks if the function returns -1 when the target is not in the list.test_empty_list: Checks the behavior for an empty list.test_multiple_occurrences: Checks what happens when the target appears multiple times in the list (it should return the index of the first occurrence).
- Assertions:
- Each test method uses
self.assertEqual()to compare the actual result fromlinear_searchwith theexpected_index.
- Each test method uses
- Running the tests:
- The
if __name__ == '__main__': block runs the tests by callingunittest.main().
- The