im new to data structures and want to ask why is my binary search giving me an error.
I've tried running in the vsc terminal and gives me a syntax error. meanwhile,the problems tab isn't showing giving me any errors. would appreciate the pointers!
def binarysearch(list,value):
if list == [] or (len(list)==1 and list[0]!= value):
return False
else:
mid = list[len(list)/2]
if mid == value:
return True
elif mid > value:
return binarysearch(list[:len(list)/2],value)
else:
return binarysearch(list[len(list)/2+1:],value)
a =[1,2,3,4,5,6,7,8]
value = 7
if binarysearch(a,value):
print("found")
else:
print("none")
The problem is in the lines that you call the recursion, the index to split must be an integer and not a float. Try the following code -
def binarysearch(list,value):
if list == [] or (len(list)==1 and list[0]!= value):
return False
else:
mid = list[int(len(list)/2)]
if mid == value:
return True
elif mid > value:
return binarysearch(list[:int(len(list)/2)],value)
else:
return binarysearch(list[int(len(list)/2)+1:],value)
a =[1,2,3,4,5,6,7,8]
value = 7
if binarysearch(a,value):
print("found")
else:
print("none")