My code for binary search function in a list returns true for a value in the list, but returns None (instead of false) for values not in the list.
Can someone please explain me what I'm doing wrong?
The program is:
def searchlist(x,alist):
end=int(len(alist)-1)
mid=int(len(alist)/2)
while len(alist)>2:
if x==alist[mid] or x==alist[0] or x==alist[end] :
return("true")
break
elif x>alist[mid]:
alist=alist[mid:]
mid=int(len(alist)/2)
end=int(len(alist)-1)
elif x<alist[mid]:
alist=alist[:mid]
mid=int(len(alist)/2)
end=int(len(alist)-1)
else:
return("false")
aList=[2,3,5,7,9,12,14,23,34,45,67,89,101]
xnum=int(input("enter a number:"))
searchlist(xnum,aList)
print(searchlist(xnum,aList))
alistis going down to 2 values and it's ending thewhileloop, causing it to returnNone. I'd suggest print out the current state of the list each loop, and manually run through your code to figure at what point it's not working as expected. Edit: Actually, it looks like yourelsestatement won't ever execute. Putreturn Falseafter the while loop instead and it should work (I'd suggest useTrueandFalseinstead of strings).elifperfomed. If you delete this block, then return('false')