Data of XYZ company is stored in sorted list Write a program for searching specific data from that list

–1 vote
Dec 3, 2019 in Python by Ramasubramanian
• 110 points

2 answers to this question.

+5 votes

This link has the program. It uses a module called bisect in python



PS: if this answer helped you, please up-vote it. If you have a suggestion, please share the same

answered Dec 3, 2019 by Raveendiran
• 960 points
0 votes

Hello @Ramasubrananiam! You can use the binary search algorithm in such situations. When you say the data is stored in a sorted list, the best approach wrt time complexity would be binary search. You can use the following code:

def binarySearch (arr, l, r, x): 
# Check base case 
    if r >= l: 
        mid = l + (r - l)/2
# If element is present at the middle itself 
    if arr[mid] == x: 
        return mid 
# If element is smaller than mid, then it can only be present in left subarray 
    elif arr[mid] > x: 
        return binarySearch(arr, l, mid-1, x) 
# Else the element can only be present in right subarray 
        return binarySearch(arr, mid+1, r, x) 
# Element is not present in the array 
        return -1
# Test array 
arr = [ 2, 3, 4, 10, 40 ] 
x = 10
# Function call 
result = binarySearch(arr, 0, len(arr)-1, x) 
if result != -1: 
    print "Element is present at index %d" % result 
    print "Element is not present in array"
answered Dec 3, 2019 by Priyanka

Related Questions In Python

+3 votes
3 answers

Write a for loop that prints all elements of a list and their position in the list. a = [4,7,3,2,5,9]

Try using this question by list comprehension: a=[4,7,3,2,5,9] print([x for ...READ MORE

answered Dec 9, 2019 in Python by vinaykumar
• 180 points
+1 vote
1 answer
0 votes
1 answer

Write code to create a list of word lengths for the words in original_str using the accumulation pattern and assign the answer to a variable num_words_list.

Hi,  num_words_list = len(original_str.split()) original_str.split() - split words in ...READ MORE

answered May 27, 2020 in Python by Niroj
• 82,820 points
0 votes
1 answer
0 votes
1 answer

How can I convert a list of dictionaries from a CSV into a JSON object in Python?

You could try using the AST module. ...READ MORE

answered Apr 17, 2018 in Python by anonymous
0 votes
0 answers

Storing a list of arrays into a CSV file and retrieving it back in a different program

This is the code that I am ...READ MORE

Jun 7, 2018 in Python by aryya
• 7,440 points
0 votes
1 answer

Is there a way to list out in-built variables and functions of Python?

The in-built variables and functions are defined ...READ MORE

answered May 14, 2019 in Python by Junaid
0 votes
1 answer

Is there a list of timezones in python?

import pytz list(pytz.common_timezones) READ MORE

answered Aug 2, 2019 in Python by Mohammad
• 3,230 points