Skip to content

Commit c8d6bab

Browse files
Enhance sentinel_linear_search doctests with edge cases and type variations
1 parent dda99e6 commit c8d6bab

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

searches/sentinel_linear_search.py

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,17 @@
1414
def sentinel_linear_search(sequence, target):
1515
"""Pure implementation of sentinel linear search algorithm in Python
1616
17-
:param sequence: some sequence with comparable items
17+
:param sequence: a mutable list with comparable items. Note: this function
18+
temporarily mutates the input list by appending and then removing the
19+
target value, but the list is restored to its original state.
1820
:param target: item value to search
1921
:return: index of found item or None if item is not found
2022
23+
The sentinel linear search algorithm works by appending the target value to the
24+
end of the list before searching. This eliminates the need for boundary checking
25+
during the loop, as the search is guaranteed to find the target (at minimum, at
26+
the end where the sentinel is placed). The input list is restored after the search.
27+
2128
Examples:
2229
>>> sentinel_linear_search([0, 5, 7, 10, 15], 0)
2330
0
@@ -30,6 +37,35 @@ def sentinel_linear_search(sequence, target):
3037
3138
>>> sentinel_linear_search([0, 5, 7, 10, 15], 6)
3239
40+
>>> sentinel_linear_search([1], 1)
41+
0
42+
43+
>>> sentinel_linear_search([1], 99)
44+
45+
>>> sentinel_linear_search([], 5)
46+
47+
>>> sentinel_linear_search([3, 1, 4, 1, 5, 9, 2, 6], 9)
48+
5
49+
50+
>>> sentinel_linear_search([3, 1, 4, 1, 5, 9, 2, 6], 1)
51+
1
52+
53+
>>> sentinel_linear_search(['a', 'b', 'c', 'd'], 'c')
54+
2
55+
56+
>>> sentinel_linear_search(['a', 'b', 'c', 'd'], 'z')
57+
58+
>>> sentinel_linear_search([1.5, 2.7, 3.14, 4.0], 3.14)
59+
2
60+
61+
>>> sentinel_linear_search([1.5, 2.7, 3.14, 4.0], 2.5)
62+
63+
>>> sentinel_linear_search([-10, -5, 0, 5, 10], -5)
64+
1
65+
66+
>>> sentinel_linear_search([-10, -5, 0, 5, 10], 0)
67+
2
68+
3369
"""
3470
sequence.append(target)
3571

0 commit comments

Comments
 (0)