Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 31 additions & 6 deletions search.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import math

class NotFoundError(Exception):
"""Custom exception raised when an element is not found in a search."""
pass


Expand All @@ -21,15 +22,40 @@ class Search:
# LINEAR SEARCH
# =====================
@staticmethod
def linear(data: List[Any], target: Any, comparator: Callable[[Any, Any], bool]) -> Any:
def linear(data: List[Any], target: Any, comparator: Callable[[Any, Any], bool]) -> int:
"""
Performs a linear search through the list.
Returns the index of the target, or -1 if not found.

Iterates through the list using a custom comparator function to find the target.
Returns the index of the first found element.

Args:
data: A list of elements to search through.
target: The element to find.
comparator: A function that takes two elements (list_element, target)
and returns True if they match.

Returns:
int: The index of the first found element.

Raises:
NotFoundError: If the target is not found in the list.
"""
pass
# Linear search iterates through the list, checking each element sequentially.
# This handles the complexity requirements (O(n) worst case, O(1) best case).
for index, element in enumerate(data):
# Use the custom comparator function as required by the assignment
# The comparator checks if the current list element matches the target
if comparator(element, target):
# Return the index immediately upon the first match.
return index

# If the loop completes without finding a match (this handles empty lists as well),
# raise the custom NotFoundError exception with the descriptive message.
raise NotFoundError(f"{target} was not found")

# =====================
# BINARY SEARCH
# BINARY SEARCH (Implementation left as 'pass' as per your original code)
# =====================
@staticmethod
def binary(data: List[Any], target: Any, comparator: Callable[[Any, Any], int]) -> Any:
Expand All @@ -42,5 +68,4 @@ def binary(data: List[Any], target: Any, comparator: Callable[[Any, Any], int])
- positive if a > b
Returns the index of the found element, or -1 if not found.
"""
pass

pass