I was Implementing a binary search function using python here is my code
def binary_search(input_array, value):
n = round(len(input_array)/2)
#print(n)
while n < len(input_array) and n>0:
if input_array[n]< value:
n = n + round(n/2)
#print(n)
elif input_array[n] > value:
n = n - round(n/2)
#print(n)
elif input_array[n] == value:
return n
return -1
here are the test cases
test_list = [1,3,9,11,15,19,29]
test_val1 = 25
test_val2 = 15
print(binary_search(test_list, test_val1))
print(binary_search(test_list, test_val2))
This code is working fine in my shell and in VSCode python debugger.
however in the Udacity course test i am getting this error
Traceback (most recent call last): File "vm_main.py", line 31, in <module> import main File "/tmp/workspaces/c1b619f1-2167-4be2-8d76-c9876c79f7a6/main.py", line 2, in <module> import studentMain File "/tmp/workspaces/c1b619f1-2167-4be2-8d76-c9876c79f7a6/studentMain.py", line 1, in <module> import algorithmsP5 File "/tmp/workspaces/c1b619f1-2167-4be2-8d76-c9876c79f7a6/algorithmsP5.py", line 30, in <module> print binary_search(test_list, test_val1) File "/tmp/workspaces/c1b619f1-2167-4be2-8d76-c9876c79f7a6/algorithmsP5.py", line 17, in binary_search if input_array[n]< value: TypeError: list indices must be integers, not float
so it states that there is a type error and that list indices must be integers not floats
but n is round(len(input_array)/2)
and round()
should return an integer value
here are the docs
round(number, ndigits=None)
Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input.
For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2). Any integer value is valid for ndigits (positive, zero, or negative). The return value is an integer if ndigits is omitted or None. Otherwise, the return value has the same type as number.
it states that if ndigits is omitted or None the return value is an integer.
so is the udacity test broken or am I missing out something
It looks like the udacity test may be using Python 2.x. Compare Python 3:
Python 3.11.2 (main, Feb 8 2023, 00:00:00) [GCC 12.2.1 20221121 (Red Hat 12.2.1-4)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> round(1/2)
0
With Python 2:
Type "help", "copyright", "credits" or "license" for more information.
>>> round(1/2)
0.0
@KellyBundy is correct and the best solution is to explicitly use integer division rather than using round()
. You could explicitly convert the return value of round
to an integer (int(round(1/2))
), but that seems like an unnecessary complication.