diff --git a/search.py b/search.py index c3f128c..54daa73 100644 --- a/search.py +++ b/search.py @@ -2,7 +2,21 @@ import math class NotFoundError(Exception): - pass + def __init__(self, message="Element not found"): + self.message = message + + def __repr__(self): + return f"NotFoundError('{self.message}')" + + def __eq__(self, other): + """Allows test comparisons with other NotFoundError objects.""" + if isinstance(other, NotFoundError): + return self.message == other.message + return False + + def __bool__(self): + """Allows checking if the result is NOT NotFoundError.""" + return False class Search: @@ -26,21 +40,39 @@ def linear(data: List[Any], target: Any, comparator: Callable[[Any, Any], bool]) Performs a linear search through the list. Returns the index of the target, or -1 if not found. """ - pass - + + if not data: + raise NotFoundError("List is empty.") + + for index, item in enumerate(data): + + if comparator(item, target): + return index + + raise NotFoundError(f"Target '{target}' not found in the list.") # ===================== # BINARY SEARCH # ===================== @staticmethod def binary(data: List[Any], target: Any, comparator: Callable[[Any, Any], int]) -> Any: - """ - Performs binary search on a sorted list. - - The comparator should return: - - 0 if a == b - - negative if a < b - - positive if a > b - Returns the index of the found element, or -1 if not found. - """ - pass + if not data: + raise NotFoundError("List is empty.") + + left, right = 0, len(data) - 1 + + while left <= right: + # Calculate mid point + mid = (left + right) // 2 + comparison_result = comparator(data[mid], target) + + if comparison_result == 0: + return mid + + elif comparison_result < 0: + left = mid + 1 + + else: + right = mid - 1 + + raise NotFoundError(f"Target '{target}' not found in the list.")