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: 13 additions & 24 deletions search.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from typing import List, Callable, Any, Optional
import math
from typing import List, Callable, Any


class NotFoundError(Exception):
pass
Expand All @@ -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")