Searches for an item in a sorted collection by interpolation search algorithm. Args: sorted_collection: sorted list of integers item: item value to search Returns: int: The index of the found item, or None if the item is not found. Examples: >>> interpo
(sorted_collection: list[int], item: int)
| 4 | |
| 5 | |
| 6 | def interpolation_search(sorted_collection: list[int], item: int) -> int | None: |
| 7 | """ |
| 8 | Searches for an item in a sorted collection by interpolation search algorithm. |
| 9 | |
| 10 | Args: |
| 11 | sorted_collection: sorted list of integers |
| 12 | item: item value to search |
| 13 | |
| 14 | Returns: |
| 15 | int: The index of the found item, or None if the item is not found. |
| 16 | Examples: |
| 17 | >>> interpolation_search([1, 2, 3, 4, 5], 2) |
| 18 | 1 |
| 19 | >>> interpolation_search([1, 2, 3, 4, 5], 4) |
| 20 | 3 |
| 21 | >>> interpolation_search([1, 2, 3, 4, 5], 6) is None |
| 22 | True |
| 23 | >>> interpolation_search([], 1) is None |
| 24 | True |
| 25 | >>> interpolation_search([100], 100) |
| 26 | 0 |
| 27 | >>> interpolation_search([1, 2, 3, 4, 5], 0) is None |
| 28 | True |
| 29 | >>> interpolation_search([1, 2, 3, 4, 5], 7) is None |
| 30 | True |
| 31 | >>> interpolation_search([1, 2, 3, 4, 5], 2) |
| 32 | 1 |
| 33 | >>> interpolation_search([1, 2, 3, 4, 5], 0) is None |
| 34 | True |
| 35 | >>> interpolation_search([1, 2, 3, 4, 5], 7) is None |
| 36 | True |
| 37 | >>> interpolation_search([1, 2, 3, 4, 5], 2) |
| 38 | 1 |
| 39 | >>> interpolation_search([5, 5, 5, 5, 5], 3) is None |
| 40 | True |
| 41 | """ |
| 42 | left = 0 |
| 43 | right = len(sorted_collection) - 1 |
| 44 | |
| 45 | while left <= right: |
| 46 | # avoid divided by 0 during interpolation |
| 47 | if sorted_collection[left] == sorted_collection[right]: |
| 48 | if sorted_collection[left] == item: |
| 49 | return left |
| 50 | return None |
| 51 | |
| 52 | point = left + ((item - sorted_collection[left]) * (right - left)) // ( |
| 53 | sorted_collection[right] - sorted_collection[left] |
| 54 | ) |
| 55 | |
| 56 | # out of range check |
| 57 | if point < 0 or point >= len(sorted_collection): |
| 58 | return None |
| 59 | |
| 60 | current_item = sorted_collection[point] |
| 61 | if current_item == item: |
| 62 | return point |
| 63 | if point < left: |
nothing calls this directly
no outgoing calls
no test coverage detected