Implement a binary search algorithm.
Searching a sorted collection is a common task. A dictionary is a sorted list of word definitions. Given a word, one can find its definition. A telephone book is a sorted list of people's names, addresses, and telephone numbers. Knowing someone's name allows one to quickly find their telephone number and address.
If the list to be searched contains more than a few items (a dozen, say) a binary search will require far fewer comparisons than a linear search, but it imposes the requirement that the list be sorted.
In computer science, a binary search or half-interval search algorithm finds the position of a specified input value (the search "key") within an array sorted by key value.
In each step, the algorithm compares the search key value with the key value of the middle element of the array.
If the keys match, then a matching element has been found and its index, or position, is returned.
Otherwise, if the search key is less than the middle element's key, then the algorithm repeats its action on the sub-array to the left of the middle element or, if the search key is greater, on the sub-array to the right.
If the remaining array to be searched is empty, then the key cannot be found in the array and a special "not found" indication is returned.
A binary search halves the number of items to check with each iteration, so locating an item (or determining its absence) takes logarithmic time. A binary search is a dichotomic divide and conquer search algorithm.
Sometimes it is necessary to raise an exception. When you do this, you should include a meaningful error message to indicate what the source of the error is. This makes your code more readable and helps significantly with debugging. Not every exercise will require you to raise an exception, but for those that do, the tests will only pass if you include a message.
To raise a message with an exception, just write it as an argument to the exception type. For example, instead of
raise Exception, you should write:
raise Exception("Meaningful message indicating the source of the error")
To run the tests, run
Alternatively, you can tell Python to run the pytest module:
python -m pytest binary_search_test.py
-v: enable verbose output
-x: stop running tests on first failure
--ff: run failures from previous test before running other test cases
For other options, see
python -m pytest -h
Note that, when trying to submit an exercise, make sure the solution is in the
You can find your Exercism workspace by running
exercism debug and looking for the line that starts with
For more detailed information about running tests, code style and linting, please see Running the Tests.
It's possible to submit an incomplete solution so you can see how others have completed the exercise.
import unittest from binary_search import find # Tests adapted from `problem-specifications//canonical-data.json` class BinarySearchTest(unittest.TestCase): def test_finds_a_value_in_an_array_with_one_element(self): self.assertEqual(find(, 6), 0) def test_finds_a_value_in_the_middle_of_an_array(self): self.assertEqual(find([1, 3, 4, 6, 8, 9, 11], 6), 3) def test_finds_a_value_at_the_beginning_of_an_array(self): self.assertEqual(find([1, 3, 4, 6, 8, 9, 11], 1), 0) def test_finds_a_value_at_the_end_of_an_array(self): self.assertEqual(find([1, 3, 4, 6, 8, 9, 11], 11), 6) def test_finds_a_value_in_an_array_of_odd_length(self): self.assertEqual( find([1, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 634], 144), 9 ) def test_finds_a_value_in_an_array_of_even_length(self): self.assertEqual(find([1, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377], 21), 5) def test_identifies_that_a_value_is_not_included_in_the_array(self): with self.assertRaisesWithMessage(ValueError): find([1, 3, 4, 6, 8, 9, 11], 7) def test_a_value_smaller_than_the_array_s_smallest_value_is_not_found(self): with self.assertRaisesWithMessage(ValueError): find([1, 3, 4, 6, 8, 9, 11], 0) def test_a_value_larger_than_the_array_s_largest_value_is_not_found(self): with self.assertRaisesWithMessage(ValueError): find([1, 3, 4, 6, 8, 9, 11], 13) def test_nothing_is_found_in_an_empty_array(self): with self.assertRaisesWithMessage(ValueError): find(, 1) def test_nothing_is_found_when_the_left_and_right_bounds_cross(self): with self.assertRaisesWithMessage(ValueError): find([1, 2], 0) # Utility functions def assertRaisesWithMessage(self, exception): return self.assertRaisesRegex(exception, r".+") if __name__ == "__main__": unittest.main()
def find(search_list, value): min_ = 0 max_ = len(search_list) - 1 while min_ <= max_: mid = (min_ + max_) // 2 if search_list[mid] < value: min_ = mid + 1 elif search_list[mid] > value: max_ = mid - 1 else: return mid raise ValueError('Item not in list')
A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.
Here are some questions to help you reflect on this solution and learn the most from it.