I am trying to solve a binary search problem, however, I keep getting an infinite loop, since the values of lo
hi
and mid
do not change as they suppose to. I am trying to search for a minimum mid value where function count_lines(mid,k) >= n
. I have spent hours debugging this code but I still couldn't figure out what is wrong with the values of lo
hi
and mid
. Could someone please look at my code and show me why this happen? Many thanks!
Failed testing case where: n=9
k=2
Here is my code:
def count_lines(v,k):
...
...
return count_lines #count_lines is an integer`
def binarySearch_v(n, k):
lo = 0
hi = n
mid = (lo + hi)//2
while (lo <= hi):
if (count_lines(mid, k) < n):
lo = mid
elif (count_lines(mid, k) > n):
hi = mid
elif (count_lines(mid, k) >= n and count_lines(mid-1, k) < n):
return mid
mid = (lo + hi) // 2
def main():
print(binarySearch_v(n,k)) # Failed at n=9 & k=2
main()