🎉 Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io 🎉
Avatar of docopeland

docopeland's solution

to Binary Search in the Python Track

Published at Mar 17 2021 · 0 comments
Test suite

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.

Exception messages

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")

Running the tests

To run the tests, run pytest binary_search_test.py

Alternatively, you can tell Python to run the pytest module: python -m pytest binary_search_test.py

Common pytest options

  • -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

Submitting Exercises

Note that, when trying to submit an exercise, make sure the solution is in the $EXERCISM_WORKSPACE/python/binary-search directory.

You can find your Exercism workspace by running exercism debug and looking for the line that starts with Workspace.

For more detailed information about running tests, code style and linting, please see Running the Tests.


Wikipedia http://en.wikipedia.org/wiki/Binary_search_algorithm

Submitting Incomplete Solutions

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], 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):
            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__":
def find(search_list:list, value,indx=0):
    half = len(search_list)//2
    if len(search_list) < 1 or (len(search_list) == 1 and search_list[half] != value):
        raise ValueError("Not in series")
    elif search_list[half] == value:
        return indx + half
    elif search_list[half] > value:
        return find(search_list[:half],value,indx)
    elif search_list[half] < value:
        return find(search_list[half:],value,half+indx)

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

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.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?