From 617dba9afda56aa3a944f57d44a619e35dc793a1 Mon Sep 17 00:00:00 2001 From: Thamsanqa Hadebe Date: Sat, 18 Oct 2025 17:27:20 +0200 Subject: [PATCH] Implemented the search algorithms --- search.py | 37 +++++++++++++------------------------ 1 file changed, 13 insertions(+), 24 deletions(-) diff --git a/search.py b/search.py index c3f128c..4df3393 100644 --- a/search.py +++ b/search.py @@ -1,5 +1,5 @@ -from typing import List, Callable, Any, Optional -import math +from typing import List, Callable, Any + class NotFoundError(Exception): pass @@ -14,33 +14,22 @@ class Search: - target: element to find - comparator: function(a, b) -> bool indicating equality or ordering - All methods return the index of the found element, or -1 if not found. + All methods return the index of the found element, or raise NotFoundError. """ - # ===================== - # LINEAR SEARCH - # ===================== @staticmethod def linear(data: List[Any], target: Any, comparator: Callable[[Any, Any], bool]) -> Any: """ - Performs a linear search through the list. - Returns the index of the target, or -1 if not found. - """ - pass + Performs a linear search through the list using a custom comparator. - # ===================== - # BINARY SEARCH - # ===================== - @staticmethod - def binary(data: List[Any], target: Any, comparator: Callable[[Any, Any], int]) -> Any: + Returns the index of the found element. + Raises NotFoundError if not found. """ - 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(f"{target} was not found") + + for index, item in enumerate(data): + if comparator(item, target): + return index + raise NotFoundError(f"{target} was not found")