-
Notifications
You must be signed in to change notification settings - Fork 0
/
generic_search.py
59 lines (42 loc) · 1.4 KB
/
generic_search.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
"""
Classic Computer Science Problems in Python
Chapter 2: Search Problems
Section 1: DNA Search
"""
from __future__ import annotations
from typing import Any, Iterable, Sequence, TypeVar
from typing_extensions import Protocol
T = TypeVar("T")
def linear_contains(iterable: Iterable[T], key: T) -> bool:
for item in iterable:
if item == key:
return True
return False
C = TypeVar("C", bound="Comparable")
class Comparable(Protocol):
def __eq__(self, other: Any) -> bool:
return self == other
def __lt__(self: C, other: C) -> bool:
return self < other
def __gt__(self: C, other: C) -> bool:
return (not self < other) and self != other
def __le__(self: C, other: C) -> bool:
return self < other or self == other
def __ge__(self: C, other: C) -> bool:
return not self < other
def binary_contains(sequence: Sequence[C], key: C) -> bool:
low: int = 0
high: int = len(sequence) - 1
while low <= high:
mid: int = (low + high) // 2
if sequence[mid] < key:
low = mid + 1
elif sequence[mid] > key:
high = mid - 1
else:
return True
return False
if __name__ == "__main__":
print(linear_contains([1, 5, 15, 15, 15, 20], 5))
print(binary_contains(["a", "d", "e", "f", "z"], "f"))
print(binary_contains(["john", "mark", "ronald", "sara"], "sheila"))