TheAlgorithms-Python

Форк
0
/
sentinel_linear_search.py 
58 строк · 1.4 Кб
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

14
def sentinel_linear_search(sequence, target):
15
    """Pure implementation of sentinel linear search algorithm in Python
16

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

21
    Examples:
22
    >>> sentinel_linear_search([0, 5, 7, 10, 15], 0)
23
    0
24

25
    >>> sentinel_linear_search([0, 5, 7, 10, 15], 15)
26
    4
27

28
    >>> sentinel_linear_search([0, 5, 7, 10, 15], 5)
29
    1
30

31
    >>> sentinel_linear_search([0, 5, 7, 10, 15], 6)
32

33
    """
34
    sequence.append(target)
35

36
    index = 0
37
    while sequence[index] != target:
38
        index += 1
39

40
    sequence.pop()
41

42
    if index == len(sequence):
43
        return None
44

45
    return index
46

47

48
if __name__ == "__main__":
49
    user_input = input("Enter numbers separated by comma:\n").strip()
50
    sequence = [int(item) for item in user_input.split(",")]
51

52
    target_input = input("Enter a single number to be found in the list:\n")
53
    target = int(target_input)
54
    result = sentinel_linear_search(sequence, target)
55
    if result is not None:
56
        print(f"{target} found at positions: {result}")
57
    else:
58
        print("Not found")
59

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.