You have stumbled upon a group of mathematicians who are also singer-songwriters. They have written a song for each of their favorite numbers, and, as you can imagine, they have a lot of favorite numbers (like 0 or 73 or 6174).
You are curious to hear the song for your favorite number, but with so many songs to wade through, finding the right song could take a while. Fortunately, they have organized their songs in a playlist sorted by the title β which is simply the number that the song is about.
You realize that you can use a binary search algorithm to quickly find a song given the title.
Your task is to implement a binary search algorithm.
A binary search algorithm finds an item in a list by repeatedly splitting it in half, only keeping the half which contains the item we're looking for. It allows us to quickly narrow down the possible locations of our item until we find it, or until we've eliminated all possible locations.
Binary search only works when a list has been sorted.
The algorithm looks like this:
Here's an example:
Let's say we're looking for the number 23 in the following sorted list: [4, 8, 12, 16, 23, 28, 32]
.
[23, 28, 32]
.[23]
.Sometimes it is necessary to raise an exception. When you do this, you should always 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. For situations where you know that the error source will be a certain type, you can choose to raise one of the built in error types, but should still include a meaningful message.
This particular exercise requires that you use the raise statement to "throw" a ValueError
when the given value is not found within the array. The tests will only pass if you both raise
the exception
and include a message with it.
To raise a ValueError
with a message, write the message as an argument to the exception
type:
# example when value is not found in the array.
raise ValueError("value not in array")
Sign up to Exercism to learn and master Python with 17 concepts, 140 exercises, and real human mentoring, all for free.