Question

Write a binary search function that, instead of returning -1 when the target value is not...

Write a binary search function that, instead of returning -1 when the target value is not in the list, raises a TargetNotFound exception (you'll need to define this exception class). Otherwise it should function normally. Name this function bin_except.

The file must be named: bin_except.py

PYTHON 3 ONLY

0 0
Add a comment Improve this question Transcribed image text
Answer #1

CODE IN PYTHON:

class TargetNotFound(Exception):
    def __init__(self, val):
        self.val = val
    def __str__(self):
        return(repr(self.val))

def binarySearch(arr, searchItem):
    size = len(arr)
    beg = 0
    end = size - 1
    while(beg < end):
        mid = (beg + end) // 2
        if arr[mid] == searchItem:
            return mid
        elif arr[mid] > searchItem:
            end = mid - 1
        else:
            beg = mid + 1
    raise TargetNotFound("TargetNotFound")

arr = []
print("Enter the numbers -1 to stop")
while(True):
    num = int(input(""))
    if num == -1:
        break
    arr.append(num)
arr.sort()
print("After sorting your list is : ", arr)
searchItem = int(input("Enter the number to search:"))
try:
    ind = binarySearch(arr, searchItem)
    print("Your number is found in the list at the index {}".format(ind))
except TargetNotFound as error:
    print(error.val)

INDENTATION:

OUTPUT:

Add a comment
Know the answer?
Add Answer to:
Write a binary search function that, instead of returning -1 when the target value is not...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Python 3 Write a binary search function that, instead of returning -1 when the target value...

    Python 3 Write a binary search function that, instead of returning -1 when the target value is not in the list, raises a TargetNotFound exception (you'll need to define this exception class). Otherwise it should function normally. Name this function bin_except. The file must be named: bin_except.py

  • In the PowerPoint slides for lecture 15, you will find a function that performs binary search...

    In the PowerPoint slides for lecture 15, you will find a function that performs binary search on a Python list using recursion. Modify that binarySearchRec(alist, item) function so that it performs ternary search on a Python list. Your new function should find two midpoints that divide the list into three approximately equal size segments. If the item being searched for is found at either of the midpoints, the function should return True. If the item being searched for is less...

  • Write a program that write a value-returning function, isVowel, that returns the value true if a...

    Write a program that write a value-returning function, isVowel, that returns the value true if a given character is a vowel and otherwise returns false. You must insert the following comments at the beginning of your program and write our commands in the middle: Write a C++ Program: /* // Name: Your Name // ID: Your ID */ using namespace std; #include <iostream> using namespace std; bool isVowel(char ch); int main() {     char ch;     …     …         ...

  • Write a recursive function that returns the minimum key value in a binary search tree of...

    Write a recursive function that returns the minimum key value in a binary search tree of distinct (positive) integers. Return -1 in case the tree is empty. (b) Write a recursive function that returns the predecessor of the key value k in a binary search tree of distinct (positive) integers. This is the key value that precedes k in an inorder traversal of the tree. If k does not exist, or if k has no predecessor, your function should return...

  • Write a class named SatData that reads a JSON file containing data on 2010 SAT results...

    Write a class named SatData that reads a JSON file containing data on 2010 SAT results for New York City and writes the data to a text file in CSV (comma-separated values) format. It just needs to read a local JSON file - it doesn't need to access the internet. Specifically, your class should have an init method that reads the file, and it should have a method named save_as_csv that takes as a parameter a list of DBNs (district...

  • project-8c Write a class named Employee that has data members for an employee's name, ID_number, salary,...

    project-8c Write a class named Employee that has data members for an employee's name, ID_number, salary, and email_address (you must use those names - don't make them private). Write a function named make_employee_dict that takes as parameters a list of names, a list of ID numbers, a list of salaries and a list of email addresses (which are all the same length). The function should take the first value of each list and use them to create an Employee object....

  • All those points need to be in the code Project 3 Iterative Linear Search, Recursive Binary...

    All those points need to be in the code Project 3 Iterative Linear Search, Recursive Binary Search, and Recursive Selection Sort Class River describes river's name and its length in miles. It provides accessor methods (getters) for both variables, toString() method that returns String representation of the river, and method isLong() that returns true if river is above 30 miles long and returns false otherwise. Class CTRivers describes collection of CT rivers. It has no data, and it provides the...

  • **JAVA** Write a binary search method for a String array that might contain nulls. Your method...

    **JAVA** Write a binary search method for a String array that might contain nulls. Your method should not crash or throw a runtime exception. See the driver program for examples. The method header is: public static int binarySearchWithNulls(String[] words, String target) must be recursive.

  • 6 (10 points Remember the recursive Searching algorithm Binary Search. Write a recursive method to search...

    6 (10 points Remember the recursive Searching algorithm Binary Search. Write a recursive method to search for a target character in the array and return the index location if found or -1 if it is not found. 7 a5 points 17 points cach) Write the code to create a GUI based class Temperature Converter which inherits from JFrame and implements the ActionListerner interface. public static int binary Search(char target, char( theValues, int firstIndex, int lastindex) Example: Clicked "F to C"...

  • Given the binary search function, answer following question: int binarySearch(int a[], int size, int target, int...

    Given the binary search function, answer following question: int binarySearch(int a[], int size, int target, int low, int high) { while (low <= high) { int mid = (low + high) / 2; if (a[mid] == target) return mid; else if (a[mid] < target) low = mid + 1; else high = mid 1: } return -1; } 1) If array a[] = {4, 5, 18, 25, 66, 70, 78}, size = 7, target = 71, low = 0, high...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT