Oscar Dolloway Oscar Dolloway - 1 month ago 19
Python Question

Binary Search small error Python 3.5

I'm creating a Binary Search for class.

It should display

True
or
False
depending if the value is within the list.

I cant get the last element without errors, my code so far:

def binarySearch(alist, value):
first = 0
last = len(alist)-1
found = False

while first <= last and not found:
midpoint = (first + last)//2
print(midpoint)
if value == midpoint:
found = True
else:
if value < alist[midpoint]:
last = midpoint-1
else:
first = midpoint+1

return found


print(binarySearch([1,2,3,4,5],5))


The line:
last = len(alist)-1
does not recognize the last element within a list? It goes to the one before last, so, if I ran the code above it would return
False
when it should return
True
.

I tried
last = len(alist)
which gives me the last element however if I try searching for a number higher than
5
it causes an
IndexError
rather than displaying
False
.

Any ideas?

Answer

You're checking the value against the index midpoint and not the values in the array.

if value == midpoint:

Should instead be:

if value == alist[midpoint]: