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
58 changes: 45 additions & 13 deletions search.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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.")