-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Expand file tree
/
Copy pathlinear.py
More file actions
28 lines (20 loc) · 806 Bytes
/
linear.py
File metadata and controls
28 lines (20 loc) · 806 Bytes
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
"""
The linear search algorithm.
"""
from typing import Optional, Sequence
from search import Key, S, T, identity
def find_index(
elements: Sequence[T], value: S, key: Key = identity
) -> Optional[int]:
"""Return the index of value in elements or None."""
for i, element in enumerate(elements):
if key(element) == value:
return i
return None
def find(elements: Sequence[T], value: S, key: Key = identity) -> Optional[T]:
"""Return an element with matching key or None."""
index = find_index(elements, value, key)
return None if index is None else elements[index]
def contains(elements: Sequence[T], value: S, key: Key = identity) -> bool:
"""Return True if value is present in elements."""
return find_index(elements, value, key) is not None