Question: In this problem, you will write a function named binary _ search ( ) with two parameters x and item. The parameter x should be
In this problem, you will write a function named binarysearch with two parameters x and item. The parameter x
should be a list containing elements with a single data type, and that is assumed to have been sorted in increasing order.
The parameter item should contain a value of the type that is contained in x
The function will apply a divideandconquer technique to recursively search the list x for an occurrence of the value stored
in item. The function should return True if item is found in x and should return False otherwise.
Write a function binarysearch that accepts two parameters named x and item.
The function should return a boolean value indicating if item was found in x by performing the following steps:
First check if item is less than the first element of x or greater than the last element of x Since x is assumed to
be sorted, if either of these conditions are true, then item is not in x and you can return False.
We split the list x into two pieces by selecting an element in the middle of the list. Create a variable named mid
that is equal to the length of x divided by rounded down. Use int to coerce the result into an integer.
If item is equal to xmid return True.
If item is less than xmid then item would have to be in the first half of x if it is there at all Slice out the
elements of x up to the index mid, pass this sublist and item to binarysearch and return the result.
If item is greater than xmid then item would have to be in the last half x if it is there at all Slice out the
elements of x after the index mid, pass this sublist and item to binarysearch and return the result.
We will now test this function.
In a new code cell, create a randomly generated list using the following lines of code:
random.seed
randomlist sortedrandomchoicesrange k
Use a loop to search randomlist for each integer Print the results of each search in the following format:
N XXXX
The character N should be replaced with the integer being search for and the characters XXXX should be replaced with
either True or False.
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
