|
| 1 | +""" |
| 2 | +Author: OMKAR PATHAK |
| 3 | +Created On: 26th August 2017 |
| 4 | +
|
| 5 | + - Best O(1) |
| 6 | + - Average O(logn) |
| 7 | + - Worst O(logn) |
| 8 | +
|
| 9 | + More info: https://en.wikipedia.org/wiki/Exponential_search |
| 10 | +""" |
| 11 | + |
| 12 | +from __future__ import division |
| 13 | +import inspect |
| 14 | + |
| 15 | +def binary_search(_list, left, right, target): |
| 16 | + if right >= left: |
| 17 | + mid = (left + right) // 2 |
| 18 | + |
| 19 | + # if element is present at the mid itself |
| 20 | + if _list[mid] == target: |
| 21 | + return mid |
| 22 | + |
| 23 | + # If the element is smaller than mid, then it |
| 24 | + # can only be present in the left subarray |
| 25 | + if _list[mid] > target: |
| 26 | + return binary_search(_list, left, mid - 1, target) |
| 27 | + |
| 28 | + # Else the element can only be present in the right |
| 29 | + return binary_search(_list, mid + 1, right, target) |
| 30 | + |
| 31 | + return False |
| 32 | + |
| 33 | +def search(_list, target): |
| 34 | + """ |
| 35 | + This function performs a exponential search |
| 36 | + on a sorted list and returns the index |
| 37 | + of item if successful else returns False |
| 38 | +
|
| 39 | + :param _list: list to search |
| 40 | + :param target: item to search for |
| 41 | + :return: index of item if successful else returns False |
| 42 | + """ |
| 43 | + |
| 44 | + if type(_list) is not list: |
| 45 | + raise TypeError("Exponential search only excepts lists, not {}".format(str(type(_list)))) |
| 46 | + |
| 47 | + # is target is at the first position itself |
| 48 | + if _list[0] == target: |
| 49 | + return 0 |
| 50 | + |
| 51 | + # Find range for binary seaarch by repeated doubling |
| 52 | + i = 1 |
| 53 | + while i < len(_list) and _list[i] <= target: |
| 54 | + i = i * 2 |
| 55 | + |
| 56 | + return binary_search(_list, i//2, min(i, len(_list)), target) |
| 57 | + |
| 58 | + |
| 59 | +def time_complexities(): |
| 60 | + """ |
| 61 | + Return information on functions |
| 62 | + time complexity |
| 63 | + :return: string |
| 64 | + """ |
| 65 | + return "Best Case: O(1), Average Case: O(logn), Worst Case: O(logn)" |
| 66 | + |
| 67 | + |
| 68 | +def get_code(): |
| 69 | + """ |
| 70 | + easily retrieve the source code |
| 71 | + of the function |
| 72 | + :return: source code |
| 73 | + """ |
| 74 | + return inspect.getsource(search) |
0 commit comments