Search code examples
pythonbinary-search

I am trying to run a binary search algorithim (Python) in terminal but nothing prints to the terminal


def binary_search(item_list,item):

    start = 0
    end = len(item_list) - 1
    found = False

    while (start <= end and not found):
        mid = (start + end) // 2
        if item_list[mid] == item:
            print(item)
            found = True
        else:
            if item_list[mid] < item:
                start = mid + 1
            else:
                end = mid -1
    return found






my_big_array = list(range(10000))
my_big_number = 256

print(my_big_array)

print(binary_search(my_big_array,my_big_number))

I try and run this in the terminal and nothing happens at all but when I create a hello_world.py file that prints hello world it works fine. Also when I try and run this file in an online python interpter it works just fine


Solution

  • I think the empty lines are the problem.

    When you paste that code into an interpreter, your binary_search function effectively turns into this:

    def binary_search(item_list,item):
        start = 0
        end = len(item_list) - 1
        found = False
    

    Because the Python interpreter completes the function definition after the first empty line it encounters. That shorter version of the binary_search function doesn't do much and also doesn't return anything.

    Try pasting your function definition in the Python interpreter with the empty lines removed.