Pure implementation of sentinel linear search algorithm in Python :param sequence: some sequence with comparable items :param target: item value to search :return: index of found item or None if item is not found Examples: >>> sentinel_linear_search([0, 5, 7, 10, 15], 0) 0
(sequence, target)
| 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__": |
no test coverage detected