Saturday, August 27, 2016

Binary search to find largest smaller element than given value python

import sys
def binary(s, num):
    l = len(s)
    mid = l/2
    #print "in binary s:" + str(s)
    #print "in binary num:" + str(num)
    #print "s[mid]:" + str(s[mid])
    if((l!=0) and  (l == 1)):
     if(s[mid] < num):
     return s[mid]
        #else:
#return None
    if((l!=0) and (l != 1)):
    if ((s[mid] >= num) and (s[mid - 1 ] < num)):
        return s[mid - 1]
    elif ((s[mid] > num) and (s[mid - 1] > num)):
        return binary(s[:mid -1] , num)
    else:
        return binary(s[mid:], num)


lst = [8,0]

print binary(sorted(lst), 4)

Output:

0

No comments:

Post a Comment