This function performs an interpolation search on a sorted list and returns the index of item if successful else returns False :param _list: list to search :param target: item to search for :return: index of item if successful else returns False
(_list, target)
| 10 | import inspect |
| 11 | |
| 12 | def search(_list, target): |
| 13 | """ |
| 14 | This function performs an interpolation search |
| 15 | on a sorted list and returns the index |
| 16 | of item if successful else returns False |
| 17 | |
| 18 | :param _list: list to search |
| 19 | :param target: item to search for |
| 20 | :return: index of item if successful else returns False |
| 21 | """ |
| 22 | |
| 23 | if type(_list) is not list: |
| 24 | raise TypeError("interpolation search only accepts lists, not {}".format(str(type(_list)))) |
| 25 | |
| 26 | # First element |
| 27 | low = 0 |
| 28 | # Last element |
| 29 | high = len(_list) - 1 |
| 30 | |
| 31 | # List is assumed to be sorted |
| 32 | while low <= high and target >= _list[low] and target <= _list[high]: |
| 33 | position = low + int(((float(high - low) / (_list[high] - _list[low])) * (target - _list[low]))) |
| 34 | |
| 35 | if _list[position] == target: |
| 36 | return position |
| 37 | |
| 38 | # If target is greater, search in right half |
| 39 | if _list[position] < target: |
| 40 | low = position + 1 |
| 41 | |
| 42 | # If target is smaller, search in left half |
| 43 | else: |
| 44 | high = position - 1 |
| 45 | |
| 46 | return False |
| 47 | |
| 48 | |
| 49 |
nothing calls this directly
no outgoing calls
no test coverage detected