Question: use python pls A variation of binary search is to 'guess' where the value might be in the list and to search there. In this
use python pls A variation of binary search is to 'guess' where the value might be in the list and to search there. In this variation of binary search, the mid index is calculated by finding the search value's weighted position between the low and high indices.
Define a function named weighted_binary_search(data, value) that performs this weighted search and returns the index of the value in the list. At each iteration, print the mid index as in the examples below. If the value is not in the list, return -1.
For example, say we have the following list and we are looking for the value 6:
[1, 1, 2, 3, 3, 6, 8, 9, 10]
We would start with our low and high indices at 0 and 8. We then compute the weighted mid index by comparing it against the values at the low and high indices to find its relative position between them:
int((6 - 1) / (10 - 1) * (8 - 0) + 0) = 4
The value at index 4 is 3 which is less than 6 so we update our low index to 5 and recompute the weighted mid index:
int((6 - 6) / (10 - 6) * (8 - 5) + 5) = 5
The value at index 5 is 6 so our search value is in the list and we return 5.
NOTE: it is possible for the approximate mid index to evaluate to a value outside the range of the list or the range of the low and high indices - in this case, the value is not in the list.
For example:
| Test | Expected | Got | ||
|---|---|---|---|---|
print(weighted_binary_search([1, 1, 2, 3, 3, 6, 8, 9, 10], 6)) | Searching mid index: 4 Searching mid index: 5 5 | |||
print(weighted_binary_search([1, 2, 3, 4, 8, 9, 10, 14, 17, 19, 20], 8)) | Searching mid index: 3 Searching mid index: 4 4 | |||
print(weighted_binary_search([1, 2, 4, 5], 3)) | Searching mid index: 1 Searching mid index: 1 -1 | |||
print(weighted_binary_search([1, 2, 4, 5], 6)) | Searching mid index: 3 -1 |
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
