Solution: Search Position
Let's look at a detailed analysis of the different ways to find the position to insert an element in a list.
We'll cover the following...
Solution: modified binary search
def search_insert_position(lst, value):"""A function to search insert position of a given value in a list:param lst: A list of integers:param value: An integer:return: The position of the value to be in the list"""size = len(lst)if size < 1:return -1start = 0end = size - 1pos = 0while start <= end:mid = start + (end - start) // 2if lst[mid] == value:return midelif lst[mid] > value:end = mid - 1pos = midelse:start = mid + 1pos = mid + 1return pos# Driver to test above codeif __name__ == '__main__':lst = [1, 3, 5, 6]value = 5print(search_insert_position(lst, value))value = 2print(search_insert_position(lst, value))
...
Access this course and 1400+ top-rated courses and projects.