-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Expand file tree
/
Copy pathrandom.py
More file actions
32 lines (24 loc) · 972 Bytes
/
random.py
File metadata and controls
32 lines (24 loc) · 972 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
29
30
31
32
"""
The random search algorithm.
"""
import random
from typing import Optional, Sequence, Set
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."""
visited: Set[int] = set()
while len(visited) < len(elements):
random_index = random.randint(0, len(elements) - 1)
visited.add(random_index)
if key(elements[random_index]) == value:
return random_index
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