ðŸŽ‰ Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io ðŸŽ‰

JimmyCarlos's solution

to Binary Search in the Python Track

Published at Apr 25 2021 · 0 comments
Instructions
Test suite
Solution

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.

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

binary_search_test.py

``````import unittest

from binary_search import find

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):
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):
"""Returns if number is in sorted list, and where it is/ where it should be inserted."""
A = search_list
if A == []: raise ValueError("Empty list.")
L,R = 0,len(A) - 1; M = (L+R)//2
if A[L] == value: return L
if A[R] == value: return R
if A[L] > value: raise ValueError("Not in list.")
if A[R] < value: raise ValueError("Not in list.")
while L < M < R:
if A[M] == value: return M
if A[M] > value: R = M
else: L = M
M = (L+R)//2
raise ValueError("Not in list.")``````