+ 1

Help!!!!!!

code is not running plz anyone correct it I don't want to use any function for binary search. x=input('no to be searched:') x=int(x) list=[1,2,3,4,5] i=0 beg=0 last=len(list)-1 mid=(beg+last)/2 while beg<last: mid=(beg+last)/2 mid=int(mid) if x<list[mid]: last=mid-1 else: if x>list[mid]: beg=mid+1 else: if x==list[mid]: print("found at ",mid)

6th Feb 2017, 12:31 AM
chitra gautam
chitra gautam - avatar
3 Respostas
+ 3
Some corrections commented ^^ x=input('no to be searched:') x=int(x) # sample list changed for not have continuous values ( and for # test search '2' which is not in list but in range of list ) list=[0,1,3,4,5] i=0 beg=0 last=len(list)-1 mid=(beg+last)/2 print('[start]\n') # debug output # if just < some cases as founding 1 in the example never reach the equality test while beg<=last: mid=(beg+last)/2 mid=int(mid) print('beg='+str(beg)+'\nlast='+str(last)) # debug output if x<list[mid]: print('( x ) '+str(x)+'<'+str(list[mid])+' ( list['+str(mid)+'] )') # debug output last=mid-1 print('last='+str(last)) # debug output # not right syntax corrected elif x>list[mid]: print('( x ) '+str(x)+'>'+str(list[mid])+' ( list['+str(mid)+'] )') # debug output beg=mid+1 print('beg='+str(beg)) # debug output # not right syntax corrected elif x==list[mid]: print("found at ",mid) # debug output # necessary to exit the loop ( if x is in list, beg<=last is always true ) # and anyway not useful to continue after found ( imagine a very big array ) break print('\n') # debug output if beg>last: # before exit the loop if x is not in list print("not found") All lines with '# debug output' comment at end, are to be erased... I let them for showing how basically debug a piece of code: study and verify the behaviour step by step, to found the bugs, a few as this search algorithm by the middle ;)
7th Feb 2017, 10:02 PM
visph
visph - avatar
+ 1
its still not searching element..it only wrks when element to be searched is at mid .. @justin
6th Feb 2017, 3:33 AM
chitra gautam
chitra gautam - avatar
0
I'm not sure what you were going for here, but this is what I came up with x=input('no to be searched:') x=int(x) list=[1,2,3,4,5] beg=0 last=len(list)-1 mid=(beg+last)/2 while beg<last: mid=(beg+last)/2 mid=int(mid) if x<list[mid]: last=mid-1 print("X <") if x>list[mid]: beg=mid+1 print("X >") if x==list[mid]: print("found at ",mid) break In Python, spacing is important.. also, you had a variable i=0 that was unused so I erased it.. also, you had else: if: I replaced that with just the if.. it was wierd to call an else than an embedded if.. if you wish, Python has an elif:
6th Feb 2017, 1:17 AM
LordHill
LordHill - avatar