-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathsolution.py
More file actions
45 lines (35 loc) · 1.02 KB
/
solution.py
File metadata and controls
45 lines (35 loc) · 1.02 KB
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
SUBMIT = True
def linear_search(_items: list[int], _target: int) -> int:
"""Find the first index of a target value in a list.
Example usage:
>>> linear_search([10, 20, 30, 40, 50], 30)
2
>>> linear_search([1, 2, 3, 4, 5], 10)
-1
>>> linear_search([], 5)
-1
"""
for i in range(len(_items)):
if _target==_items[i]:
return i
return -1
def test() -> None:
"""Simple self-test for Linear Search."""
cases = [
(([10, 20, 30, 40, 50], 30), 2),
(([1, 2, 3, 4, 5], 10), -1),
(([], 5), -1),
(([1, 1, 1], 1), 0),
]
for (items, target), expected in cases:
try:
res = linear_search(items, target)
assert res == expected, (
f"Failed for search {target} in {items}: expected {expected}, got {res}"
)
except AssertionError as e:
print(f"❌ {e}")
return
print("✅ All tests passed!")
if __name__ == "__main__":
test()