Hi,
I successfully submitted my solution to binary search. However I came across a strange behaviour in my own dev environment.
Although the values 4 and 8
are contained in the list [1, 3, 4, 6, 8, 9, 11]
, my code raises ValueError("value not in array")
only on these two values. Because these values are not tested explicitly, the code passes the test.
I tested out the values by manually changing the binary_search_test.py
values and as expected, the test didn’t pass, see code.
This is the test file on GitHub https://github.com/exercism/python/blob/main/exercises/practice/binary-search/binary_search_test.py
Test starts at line17
def test_finds_a_value_in_the_middle_of_an_array(self):
self.assertEqual(find([1, 3, 4, 6, 8, 9, 11], 6), 3)
# fails => self.assertEqual(find([1, 3, 4, 6, 8, 9, 11], 4), 2)
# fails => self.assertEqual(find([1, 3, 4, 6, 8, 9, 11], 8), 4)
I still don’t understand, why my code behaves like that and I am not proficient enough, to help solve this issue in the testing.
For reference, here is my code, but I don’t expect it to be solved here. I just want the test to catch errors in the code
Thanks Murat
def find(search_list: list[int], value: int) -> int:
sorted_list = sorted(search_list)
left, right = 0, len(search_list) - 1
if not search_list:
raise ValueError("value not in array")
if search_list[0] == value:
return 0
elif search_list[-1] == value:
return len(search_list) - 1
while left < right:
mid = left + (right - left) // 2
if sorted_list[mid] == value:
return mid
elif sorted_list[mid] < value:
left = mid + 1
else:
right = mid - 1
raise ValueError("value not in array")