(adsbygoogle = window.adsbygoogle || []).push({});
Hey guys, im trying to write a binary search program and it finds the number if it is in the list, however when the number is not in the list it errors instead of just saying it can't find the number, can someone please correct this code for me so that it works, thanks.
def binarysearch(First, Last, Usernumber, Listofnumbers, Middle):
NumberFound = False
Numbernotfound = False
if Usernumber == Listofnumbers[int(Middle)]:
NumberFound = True
elif First == Last :
Numbernotfound = True
else:
if Usernumber > Listofnumbers[int(Middle)]:
binarysearch(Middle,Last,Usernumber,Listofnumbers,First+((Last-Middle)/2))
else:
binarysearch(First,Middle,Usernumber,Listofnumbers,First+((Last-Middle)/2))
if NumberFound == True:
print("You found it at " + str(First+((Last-First)/2)))
elif Numbernotfound == True:
print("number not found")
import math
Listofnumbers = [4, 7, 13, 18, 22, 26, 31, 33, 38, 44, 52, 60, 66, 71, 75, 79, 83, 89, 94, 99]
Usernumber = int(input("Please enter a number"))
First = 0
Last = len(Listofnumbers)
Middle = int(math.floor(First+((Last-First)/2)))
binarysearch(First, Last, Usernumber, Listofnumbers, Middle)
Last edited by
Gandi ; 09-13-2010 at 11:17 AM.
Reason: The code is not indenting when pasted in... sorry