shubham
shubham

Reputation: 83

ERROR: List indices must be integers or slices, not float in below binary search program in python, please find me a solution

I am trying to execute binary search program and i am getting an error, ERROR: List indices must be integers or slices, not float. Please help.

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 ] 
x = 10

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

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

Upvotes: 0

Views: 409

Answers (2)

shubham
shubham

Reputation: 83

Finally found it.

At line 6, mid = l + (r - l)/2

changed it to

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

and successful.

Upvotes: 0

ForceBru
ForceBru

Reputation: 44888

You're using Python 3.x, where division results in a floating-point number, so mid in mid = l + (r - l)/2 is actually a float, but then you attempt to do arr[mid], which is an error because lists cannot be indexed by floating-point numbers.

If you want integer division, do this:

mid = l + (r - l)//2 # double slash

Upvotes: 1

Related Questions