[Python] Python recursive binary search function not working but cannot see why

Discussão em 'Python' iniciado por Stack, Setembro 15, 2024.

  1. Stack

    Stack Membro Participativo

    all this is my first time posting here. I've got a recursive binary search function which should work. But isn't. It has an if condition that uses the 'or' logical operator to test whether a key is outside the bounds of an input array. That seems to be the source of the problem. The if condition works outside my recursive function but doesn't seem to work inside it. It's most likely a small issue but I cannot see what that issue could be

    A = [31,48,59,62,71,75,81]
    L=0
    R=len(A)-1
    key = 71

    def recur_binary_search(A, L, R, key):
    if key < A[L] or key > A[R]:
    return -1
    M = (L + R) // 2
    if key < A[M]:
    return recur_binary_search(A,L,M-1,key)
    elif key > A[M]:
    return recur_binary_search(A,L,M+1,key)
    else:
    return M

    print( recur_binary_search(A, L, R, key))
    # my code keeps returning -1 rather than the correct value, 4.


    I expected an output of 4, but I keep getting a value of -1 returned. This seems to be caused by this if condition

    if key < A[L] or key > A[R]:
    return -1


    But, I just cannot see how that if condition, could ever evaluate to true at the start of the function. My function can see A[L] which is 31. It can see A[R] which is 81 (verified via print statements) and it can see the key. The key is 71.

    So, how is this if evaluating to true? As I said, I'm sure it is a small issue but I can't see what it is.

    Continue reading...

Compartilhe esta Página