-1

I have this code:

def binary_search(list, item):
    low = 0
    high = len(list)-1
    
    while low <= high:
        mid = (low + high)/2
        guess = list[mid]
        
        if guess == item:
            return mid
        if guess > item:
            high = mid - 1
        else:
            low = mid +1
    return None

my_list = [1,3,5,7,9]

print binary_search(my_list, 3)

I want the code to perform a binary search of my_list, looking for the value 3 and returning its index.

But I get a syntax error from line 19: print binary_search(my_list, 3)

What is wrong with the code?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
underd0g
  • 1
  • 1
  • it should be like this `print(binary_search(my_list, 3))` you forget open round parethesis!! – Yash Mehta Mar 17 '23 at 06:29
  • 1
    also this should be `mid = (low + high)/2` [float]-> `mid = (low + high)//2` [int] – Yash Mehta Mar 17 '23 at 06:31
  • `print binary_search(my_list, 3)` - this is python 2 syntax and also you should use integer division '//' when calculating the middle index, regular division returns a float. `mid = (low + high)//2` – Ake Mar 17 '23 at 06:33
  • index of list should be int: `mid = int((low + high) / 2)` – pyjedy Mar 17 '23 at 06:34
  • other than that don't use variable name as `list` cause it is one of the data structure in python.! – Yash Mehta Mar 17 '23 at 06:35
  • If you are learning Python from a Python 2 course, probably switch to one which covers Python 3 instead. Python 2 was end-of-lifed in 2020 and is not worth learning except for very specific scenarios, and even then probably start with Python 3 and then learn the differences. – tripleee Mar 17 '23 at 06:37

1 Answers1

1

Making these minor changes will make the code work
1.Use brackets in the print statement
2."mid" is supplied as an index so it should not be float and be an integer so use "//" for divide
binary_search(list,x)
list -> list of integers
x -> integer whose position is needed

def binary_search(list, item): 
  low = 0 
  high = len(list)-1

  while low <= high:
    mid = (low + high)//2
    guess = list[mid]
    
    if guess == item:
        return mid
    if guess > item:
        high = mid - 1
    else:
        low = mid +1
  return None

my_list = [1,3,5,7,9]

print( binary_search(my_list, 3))