So I've been trying to make a program that uses binary search for school, however whenever I try to run it, it comes back with an error of 'TypeError: list indices must be integers or slices, not NoneType'
This is the code:
arr = [1,2,3,4,5,6,7]
find = 3
if len(arr)%2 != 0:
half = int(len(arr)+1)
else:
half = int(len(arr))
half = half/2
half = int(half)
while True:
half = int(half)
sort = arr[half]
print(sort)
if find < sort:
half = print(half/2)
elif find > sort:
half = half+(half/2)
elif find == sort:
print(f"found at position {half}")
I clearly state that it is an integer, but it just doesn't work and I don't know why
Your problem is the line half = print(half/2)
. print is a function that doesn't return anything (therefore it returns None
), and you are assigning None to half then. You probably mean half = half/2
, and if you want to print it, do so on the next line.
Also, take a look at the difference between /
and //
in python. If you use //
to divide by two, it will always return an integer and you won't need to manually convert it to an int using half = int(half)
.