Skip to content

Commit 758439c

Browse files
authored
Merge pull request TheAlgorithms#385 from kelvins/sentinel_linear_search
searches: add sentinel linear search algorithm
2 parents a31d20a + d2e77b0 commit 758439c

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

searches/sentinel_linear_search.py

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
"""
2+
This is pure python implementation of sentinel linear search algorithm
3+
4+
For doctests run following command:
5+
python -m doctest -v sentinel_linear_search.py
6+
or
7+
python3 -m doctest -v sentinel_linear_search.py
8+
9+
For manual testing run:
10+
python sentinel_linear_search.py
11+
"""
12+
13+
def sentinel_linear_search(sequence, target):
14+
"""Pure implementation of sentinel linear search algorithm in Python
15+
16+
:param sequence: some sequence with comparable items
17+
:param target: item value to search
18+
:return: index of found item or None if item is not found
19+
20+
Examples:
21+
>>> sentinel_linear_search([0, 5, 7, 10, 15], 0)
22+
0
23+
24+
>>> sentinel_linear_search([0, 5, 7, 10, 15], 15)
25+
4
26+
27+
>>> sentinel_linear_search([0, 5, 7, 10, 15], 5)
28+
1
29+
30+
>>> sentinel_linear_search([0, 5, 7, 10, 15], 6)
31+
32+
"""
33+
sequence.append(target)
34+
35+
index = 0
36+
while sequence[index] != target:
37+
index += 1
38+
39+
sequence.pop()
40+
41+
if index == len(sequence):
42+
return None
43+
44+
return index
45+
46+
47+
if __name__ == '__main__':
48+
try:
49+
raw_input # Python 2
50+
except NameError:
51+
raw_input = input # Python 3
52+
53+
user_input = raw_input('Enter numbers separated by comma:\n').strip()
54+
sequence = [int(item) for item in user_input.split(',')]
55+
56+
target_input = raw_input('Enter a single number to be found in the list:\n')
57+
target = int(target_input)
58+
result = sentinel_linear_search(sequence, target)
59+
if result is not None:
60+
print('{} found at positions: {}'.format(target, result))
61+
else:
62+
print('Not found')

0 commit comments

Comments
 (0)