-1

I am trying to code binary search function recursively in Python. I just want to return True or False depending on the search result. In some True cases, I get None. I don't understand what is wrong with my for loops.

Help me, please! Thanks

def func(data, key):
    '''
    data: input list
    key: the number to be searched
    output: return Boolean
    '''
    low = 0
    high = len(data)
    mid = (low+high)//2
    if(key>data[high-1]):
        return False
    if(data[mid]==key):
        return True
    elif(key>data[mid]):
        search_sorted_rec(data[mid+1:high],key)
    elif(key<data[mid]):
        search_sorted_rec(data[low:mid],key)

data1=func((1,2,3,4,5,6,7,8),8)

print(data1) # I got None
Cem O.
  • 3
  • 4

1 Answers1

1

You're doing a recursive function. So at the recursive call, you return the result. So not:

elif(key>data[mid]):
    search_sorted_rec(data[mid+1:high],key)

But instead:

elif(key>data[mid]):
    return search_sorted_rec(data[mid+1:high],key)
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173