n python. Please do not copy from other websites, as it is incorrect and I'd like to be able to apply this to future problems. Thanks. Alter the binary search function below so that, instead of returning -1 when the target value is not in the list, it raises a TargetNotFound exception (you'll need to define this exception class). Otherwise it should function as normal.
In python.
Please do not copy from other websites, as it is incorrect and I'd like to be able to apply this to future problems. Thanks. Alter the binary search function below so that, instead of returning -1 when the target value is not in the list, it raises a TargetNotFound exception (you'll need to define this exception class). Otherwise it should function as normal.
def binary_search(a_list, target):
"""
Searches a_list for an occurrence of target
If found, returns the index of its position in the list
If not found, returns -1, indicating the target value isn't in the list
"""
first = 0
last = len(a_list) - 1
while first <= last:
middle = (first + last) // 2
if a_list[middle] == target:
return middle
if a_list[middle] > target:
last = middle - 1
else:
first = middle + 1
return -1
Trending now
This is a popular solution!
Step by step
Solved in 3 steps with 1 images