-1

I implemented a recursive way of binary search and I'm facing a problem. Ths is my code:

def foo(x, ls):
    left, right = 0, len(ls)-1
    def search(l, r):
        if l>r:
            return False
        mid = (l+r)//2
        if x < ls[mid]:
            return search(l,mid-1)
        elif x > ls[mid]:
            return search(mid+1,r)
        else:
            return True

    return search(left,right)

this function works fine. However if I remove the return from the if statements, and call search function without a return, it raises wrong answers. Can anyone explain this? What is the exact difference?

KoZark
  • 85
  • 7
  • I don't get what you're asking. You created a code that works, and you wonder why breaking it doesn't work? – Ofer Sadan Dec 07 '19 at 15:43
  • No, i dont wanna break it. I just asking the diference between recursing with return statement and without. – KoZark Dec 07 '19 at 15:45
  • 1
    Because without `return` you're running the same code but the calculation being done just disappears when it's done. `return` does just that, it returns the result you worked hard to get. – Ofer Sadan Dec 07 '19 at 15:49

1 Answers1

1

If you don't return a value in a recursive function, the tail of this function is just returning None, which is evaluated to False if you try to convert it to boolean value