Inlab 7

In a small village library, books are lended to the members for a period of one week. Details such as name of the book, author, date of purchase, accession number and availability status are stored for each book. Given the details of the 'n' books sorted by the accession number of book and an accession number to search, develop an algorithm and write the Python code to perform binary search in the given data. Print 'Found' or 'Not Found' appropriately.
Input Format
First line contains the number of books in the library, n
Next n*5 lines contains the details of the book in the following order:
name of the book
author of the book
date of purchase of the book
accession number of the book
availability status of the book
Next line contains the accession number of book to be searched 'n'
Output Format
Print Found or Not Found

Program:
def bsearch(n_list,num):
    low = 0
    high = len(n_list) - 1
    while low!=high-1:
        mid = (low+high)//2
        if n_list[mid] == num:
            return 'Found'
        elif n_list[mid] > num:
            high = mid
        elif n_list[mid] < num:
            low = mid
    else:
        if n_list[low] == num or n_list[high]==num:
            return 'Found'
        else:
            return 'Not Found'
n_list = []
n = int(input())
for i in range(n):
    temp_list = []
    for j in range(5):
        if j == 3:
            accession_num = int(input())
            n_list.append(accession_num)
        else:
            temp_list.append(input().rstrip())
num_search = int(input())
n_list.sort()
print(bsearch(n_list,num_search))


Algorithm:
Step1. define bsearch function with two parameters n_list and num
Step1.1 assign low as 0,high as the length of the list minus one and mid as one
Step1.2 repeat till low is not equal to mid
Step1.2.1 check if the num entered is equal to the middle element in the list if so then print found else if the middle element is greater than num then assign high as mid else if the middle element is less than num then assign low as mid
Step1.3 if the function has not returned None till now then print Not Found and return None
Step2. get the number of books.
Step3. get the details of the book and assign these details to the dictionary n_list with accession number as the key and all the other things as the value
Step4. get the accession number of the number that needs to be searched.
Step5. call the bsearch function to perform binary search and to check whether the accession number is found or not
Step6. End



3 comments:

Bonus Practice Problems(GMT To IST)

IST (Indian Standard Time) is 5 hours 30 minutes ahead of GMT(Greenwich Mean Time). Develop an algorithm and write the Python code to find...