Search code examples
runtime-errorbinary-searchpython-3.7

Learning Binary Search in python 3.7


I found this code on https://www.geeksforgeeks.org/binary-search/

# Python Program for recursive binary search.

# Returns index of x in arr if present, else -1
def binarySearch (arr, l, r, x):

    # Check base case
    if r >= l:

        mid = l + (r - l)/2;

    # If element is present at the middle itself
    if arr[mid] == x:
        return mid

    # If element is smaller than mid, then it 
    # can only be present in left subarray
    elif arr[mid] > x:
        return binarySearch(arr, l, mid-1, x)

    # Else the element can only be present 
    # in right subarray
    else:
        return binarySearch(arr, mid+1, r, x)

    else:
        # Element is not present in the array
        return -1

# Test array
arr = [ 2, 3, 4, 10, 40, 50, 80, 140, 200, 2000, 100]
x = 50

# Function call
result = binarySearch(arr, 0, len(arr)-1, int)

if result != -1:
    print ("Element is present at index %d" % result)
else:
    print ("Element is not present in array")

However, when I run it I get this problem: TypeError: list indices must be integers or slices, not float I'm not sure how to convert do that. I attempted to set the entire array as an int but that didn't work or replace x with int and that didn't work either.

Any suggestion?


Solution

  • The issue is on this line:

    mid = l + (r - l)/2;
    

    In Python 3 / does floating point division and as mid is used as an array index it needs to be an int. To do integer division use //

    mid = l + (r - l) // 2;
    

    There is also another issue with the call to the function:

    result = binarySearch(arr, 0, len(arr) - 1, int)
    

    The last parameter should not be int but x (the variable you are searching for):

    result = binarySearch(arr, 0, len(arr) - 1, x)
    

    when you pass in int as the last parameter you'll get an error TypeError: unorderable types: int() > type()