Write a Python function that implements binary search. The function takes two parameters – a file name and the value it is searching for. Your function should read in this file and similarly formatted files. Assume that the input file, such as data.txt, is sorted. Your code should return two values: (1) the number of comparisons performed to find/not find the value and (2) the index position of the value (or -1 if it is not found). Please comment on code so I can better understand. Try not to use any online sources because l've probably already looked at them and I want further understanding, if so please link them so I know if l've already searched through that example.

Database System Concepts
7th Edition
ISBN:9780078022159
Author:Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Publisher:Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Chapter1: Introduction
Section: Chapter Questions
Problem 1PE
icon
Related questions
Question

Thank you

Write a Python function that implements binary search. The function takes two parameters – a
file name and the value it is searching for. Your function should read in this file and similarly
formatted files. Assume that the input file, such as data.txt, is sorted. Your code should return
two values: (1) the number of comparisons performed to find/not find the value and (2) the
index position of the value (or -1 if it is not found). Please comment on code so I can better
understand. Try not to use any online sources because l've probably already looked at them
and I want further understanding, if so please link them so I know if l've already searched
through that example.
Transcribed Image Text:Write a Python function that implements binary search. The function takes two parameters – a file name and the value it is searching for. Your function should read in this file and similarly formatted files. Assume that the input file, such as data.txt, is sorted. Your code should return two values: (1) the number of comparisons performed to find/not find the value and (2) the index position of the value (or -1 if it is not found). Please comment on code so I can better understand. Try not to use any online sources because l've probably already looked at them and I want further understanding, if so please link them so I know if l've already searched through that example.
Expert Solution
Step 1

EXPLANATION: -

Main operations involved: -

  • Reading the sorted text data file.
  • Splitting the data based on space and storing it in the string list.
  • Casting all string elements of string list to integer and storing in integer list.
  • Using a helper_function to find the comparisons being done, and index of the key being searched in sorted_list

def binary_search(file_name, key):

  • This function opens the file to read.
  • It reads the file using the read function.
  • Then the file pointer is closed.
  • The extra space from both sides of the string is removed using the strip function.
  • The read string is split based on a single space and stored in a string list.
  • The string list is traversed in for loop, each element is cast to int and appended in an empty integer list.
  • A call to the helper binary search function is made by passing the int_list and key to be searched in int_list
  • In the end, the function returns the comparison count and key index.

def helper_binary_search(my_list, key):

  • This function takes arguments as a list and key to be searched in the list.
  • The required variables like the number of comparisons, the left, right indexes are being defined.
  • The while loop runs till the left is less than or equal to right index.
  • In each iteration, the floor value of the left and right index is calculated and stored in mid variable.
  • if the element at the mid index is less than key, then the value of left index is incremented to mid to 1, and the comparison count is increment by 1 since only 1 comparison is done.
  • If not the elif condition is checked, here total comparisons are done , one of if block, then elif block.
    • if the element at mid index is more than key, then the value of left index is set to mid - 1, and the comparison count is increment by 2.
  • else the key is found in list, hence the comparison count is incremented by 2. one for if block, and other for elif block
  • Now the comparions and mid index is returned as a result.
  • If the key is not found, then comparisons count and -1 is returned.
Step 2

#WORKING CODE

import math

#helper_binary_search function
def helper_binary_search(my_list, key):
    comparisons = 0
    element_count = len(my_list)
    left = 0
    right = element_count -1
    
    while left <= right:
        #taking integer floor value
        mid = math.floor((left + right)/2)
        #if key greater than mid index element in my_list
        if my_list[mid] < key:
            left = mid + 1
            comparisons = comparisons + 1
        #if key less than mid index element in my_list
        elif my_list[mid] > key:
            right = mid - 1
            comparisons = comparisons + 2
        #if key is found in my_list
        else:
            comparisons = comparisons + 2
            return comparisons,mid
    return comparisons,-1

#function to work on file 
def binary_search(file_name, key):
    #defining empty list
    int_list = []
    
    #open the list in read mode
    file_pointer = open(file_name, 'r')

    # read the whole file now in one go
    data = file_pointer.read()
    #close the file reader
    file_pointer.close()  
    
    #processing the file data
    #remove extra space from end from both sides
    data = data.strip()
    
    #split the string based on space
    str_list = data.split(' ')
    
    #convert all elements to integer one by one
    for element in str_list:
        num = int(element)  
        #append num in int_list
        int_list.append(num)
        
    print('File Data being read: ',int_list) #contents of int_list now

    #helper binary_search to find comparisons and key index if present
    num_of_comparisons, key_index = helper_binary_search(int_list,key)

    return num_of_comparisons, key_index

#main function
def main():
    print(binary_search('data.txt', 78))    

#calling the main function
if __name__ == "__main__":
    main()

steps

Step by step

Solved in 3 steps with 1 images

Blurred answer
Knowledge Booster
Hyperlinks
Learn more about
Need a deep-dive on the concept behind this application? Look no further. Learn more about this topic, computer-science and related others by exploring similar questions and additional content below.
Similar questions
  • SEE MORE QUESTIONS
Recommended textbooks for you
Database System Concepts
Database System Concepts
Computer Science
ISBN:
9780078022159
Author:
Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Publisher:
McGraw-Hill Education
Starting Out with Python (4th Edition)
Starting Out with Python (4th Edition)
Computer Science
ISBN:
9780134444321
Author:
Tony Gaddis
Publisher:
PEARSON
Digital Fundamentals (11th Edition)
Digital Fundamentals (11th Edition)
Computer Science
ISBN:
9780132737968
Author:
Thomas L. Floyd
Publisher:
PEARSON
C How to Program (8th Edition)
C How to Program (8th Edition)
Computer Science
ISBN:
9780133976892
Author:
Paul J. Deitel, Harvey Deitel
Publisher:
PEARSON
Database Systems: Design, Implementation, & Manag…
Database Systems: Design, Implementation, & Manag…
Computer Science
ISBN:
9781337627900
Author:
Carlos Coronel, Steven Morris
Publisher:
Cengage Learning
Programmable Logic Controllers
Programmable Logic Controllers
Computer Science
ISBN:
9780073373843
Author:
Frank D. Petruzella
Publisher:
McGraw-Hill Education