-1
def binarySearch( a, l, r, num ):

    m = (l+r) // 2

    if l < r:

        if num <= a[m]:
            binarySearch(a, l, m, num)
        else:
            binarySearch(a, m+1, r, num)

    else:

        print( m )

If instead of print(m) i write return(m) and then try to print the function it returns None and I don't understand why. Can someone explain? Thanks

awesoon
  • 32,469
  • 11
  • 74
  • 99

1 Answers1

0
def binarySearch( a, l, r, num ):

    m = (l+r) // 2

    if l < r:

        if num == a[m]:
            return m

        elif num < a[m]:
            return binarySearch(a, l, m, num)

        else:
            return binarySearch(a, m+1, r, num)
    else:
        return  -1

 # If return statement with the thing that need to be return is not mentioned explicitly  by default we get None 

'''
--tested using
for i in range(0,8):
    print('result for item', i ,binarySearch( [0,1,2,5,7], 0, 5,i )) 
'''
Tanmay jain
  • 814
  • 6
  • 11