TheAlgorithms-Python
58 строк · 1.4 Кб
1"""
2This is pure Python implementation of sentinel linear search algorithm
3
4For doctests run following command:
5python -m doctest -v sentinel_linear_search.py
6or
7python3 -m doctest -v sentinel_linear_search.py
8
9For manual testing run:
10python sentinel_linear_search.py
11"""
12
13
14def sentinel_linear_search(sequence, target):15"""Pure implementation of sentinel linear search algorithm in Python16
17:param sequence: some sequence with comparable items
18:param target: item value to search
19:return: index of found item or None if item is not found
20
21Examples:
22>>> sentinel_linear_search([0, 5, 7, 10, 15], 0)
230
24
25>>> sentinel_linear_search([0, 5, 7, 10, 15], 15)
264
27
28>>> sentinel_linear_search([0, 5, 7, 10, 15], 5)
291
30
31>>> sentinel_linear_search([0, 5, 7, 10, 15], 6)
32
33"""
34sequence.append(target)35
36index = 037while sequence[index] != target:38index += 139
40sequence.pop()41
42if index == len(sequence):43return None44
45return index46
47
48if __name__ == "__main__":49user_input = input("Enter numbers separated by comma:\n").strip()50sequence = [int(item) for item in user_input.split(",")]51
52target_input = input("Enter a single number to be found in the list:\n")53target = int(target_input)54result = sentinel_linear_search(sequence, target)55if result is not None:56print(f"{target} found at positions: {result}")57else:58print("Not found")59