0

So i tried to do binary search in python, which i think syntactically right, but logically somewhere going wrong, despite of checking it infinite times. Here is my code.

def m(a,ele):
    a=a
    ele=ele

    length = len(a)
    if length <=1:
        return a
    mid = a[length//2]

    if ele == mid:
        return True
    elif ele > mid:
        print("if")
        if len( a[a.index(mid):]) == 0:
            return False
        elif len( a[a.index(mid):]) ==1 and ele !=  a[a.index(mid):]:
            return False
        elif len( a[a.index(mid):]) ==1 and ele ==  a[a.index(mid):]:
            return True
        else:
            m( a[a.index(mid):],ele)
    else:
        print("else")
        if len( a[:a.index(mid)]) == 0:
            return False
        elif len( a[:a.index(mid)]) ==1 and ele !=  a[:a.index(mid)]:
            return False
        elif len( a[:a.index(mid)]) ==1 and ele ==  a[:a.index(mid)]:
            return True
        else:
            m( a[:a.index(mid)],ele)


print(m([1,3,6,8],8))

SO, in this case it should print True but it is printing None. Any help regarding this code would be helpful, i know i am doing some silly mistakes.

2
  • 3
    You need to return the result of recursion. i.e: return m( a[a.index(mid):],ele) Commented May 12, 2020 at 16:50
  • ahhhhh, Such a silly mistake! thank you for pointing out. Commented May 12, 2020 at 16:51

2 Answers 2

1

You need to return the result of each step of recursion. (In all the else's)

else:
       return m( a[a.index(mid):],ele)
Sign up to request clarification or add additional context in comments.

Comments

1

THank you people for correcting me. So this is my final code

def m(a,ele):
    a=a
    ele=ele

    length = len(a)
    if length <=1:
        return a
    mid = a[length//2]

    if ele == mid:
        return True
    elif ele > mid:
        if len( a[a.index(mid):]) == 0:
            return False
        elif len( a[a.index(mid):]) ==1 and ele !=  a[a.index(mid):][0]:
            return False
        elif len( a[a.index(mid):]) ==1 and ele ==  a[a.index(mid):][0]:
            return True
        else:
            return m( a[a.index(mid):],ele)
    else:
        if len( a[:a.index(mid)]) == 0:
            return False
        elif len( a[:a.index(mid)]) ==1 and ele !=  a[:a.index(mid)][0]:
            return False
        elif len( a[:a.index(mid)]) ==1 and ele ==  a[:a.index(mid)][0]:
            return True
        else:
            return m( a[:a.index(mid)],ele)


print(m([1,3,6,8,77,777],777))
True

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.