Question

In: Computer Science

Consider following Bisectional search implementation that prints the location of the elements found in a given...

Consider following Bisectional search implementation that prints the location of the elements found in a given sorted list. If not found it prints -1. Modify the program such that it would provide: • All the places in the list where the element was found • How many times the element appeared in the list.

#Bisectional search (return one of the locations)
def bisectioanl_search(L,k, low, high):
 if high>=low:
 mid = (low + high) // 2
 if L[mid]==k:
 return mid
 elif L[mid]>k:
 return bisectioanl_search(L,k,low,mid-1)
 else:
 return bisectioanl_search(L, k, mid+1,
high)
 else:
 return -1
L=[2,5,8,12,15,15,19,21,26,36,39,41,45,50,53]
k=15
print(bisectioanl_search(L,k,0,len(L)))

NOTE: This program should need to be done in Python programming

Solutions

Expert Solution

#Bisectional search (return one of the locations)

def bisectioanl_search(L,k, low, high):
 if high>=low:
  mid = (low + high) // 2
  if L[mid]==k:
    return mid
  elif L[mid]>k:
    return bisectioanl_search(L,k,low,mid-1)
  else:
    return bisectioanl_search(L, k, mid+1,high)
 else:
  return -1

if __name__ == "__main__":
  indexes = []
  L=[2,5,8,12,12,12,12,15,15,19,21,26,36,39,41,45,50,53]
  k=12
  while True :
    val = bisectioanl_search(L,k,0,len(L))
    if val==-1:
      break
    else:
      L.pop(val)
      if indexes:
        new = max(indexes)
        indexes.append(new+1)
      else:
        indexes.append(val)
     
  ind = ','.join([str(x) for x in indexes])
  if ind:
    print("The element",k,"was found in",ind,"location(s).")
    print("The element",k,"appeared in the list",len(indexes),"times.")
  else:
    print("The element",k,"not found")

If you want to use reccursion than we can't modify the function as it is calling itself again and again instead we can do a trick to append the indexes in a list everytime it gets the index of the key and call the same function after deleting the index value. As it will always a sorted array to the same value indexes should be in increasing order.

There is another way wothout reccursion. You can do either of them.

def bisectional_search(lst,x,l,r): 
    loc = []
    while l <= r: 
        mid = l + (r - l) // 2; 
          
        # Check if x is present at mid 
        if lst[mid] == x:
            lst.pop(mid)
            if loc:
              new = max(loc) #max of index+1
              loc.append(new+1)
            else:
              loc.append(mid)
  
        # If x is greater, ignore left half 
        elif lst[mid] < x: 
            l = mid + 1
  
        # If x is smaller, ignore right half 
        else: 
            r = mid - 1
    if loc:
      return loc
    else:
      return -1 #not present
  
# Driver Code 
L=[2,5,8,12,15,15,15,19,21,26,36,39,41,45,50,53]
k=15
# Function call 
result = binarySearch(L, 0, len(arr), k)
if result != -1: 
    ind = ','.join([str(p) for p in result]) 
    print ("Element is present at index ", ind) 
    print ("Element is present in the list ", len(result),"times")
else: 
  
    print ("Element is not present in array") 

Any query you can as in the comment.


Related Solutions

Consider following Bisectional search implementation that prints the location of the elements found in a given...
Consider following Bisectional search implementation that prints the location of the elements found in a given sorted list. If not found it prints -1. Modify the program such that it would provide: • All the places in the list where the element was found • How many times the element appeared in the list. NOTE Answer should be in python.
In C++ Consider the binary search tree implementation in file bintree.cp a)Add to the TreeNode class...
In C++ Consider the binary search tree implementation in file bintree.cp a)Add to the TreeNode class a pointer to the parent node. Modify the insert and erase functions to properly set those pointers. b)Then define a TreeIterator class that contains a pointer to a TreeNode and has member functions get and next. i)The iterator’s get member function should return the data value of the node to which it points. ii)The iterator’s next member function should find the next element in...
Write a pseudocode or java code implementation for linear search that searches elements based on a key value from an array of undetermined length
Write a pseudocode or java code implementation for linear search that searches elements based on a key value from an array of undetermined lengthJAVA
Given a binary search tree T with n elements. For any two keys k1 and k2...
Given a binary search tree T with n elements. For any two keys k1 and k2 such that k1 < k2, there is an algorithm to print all elements x in T such that k1 ≤x ≤k2 in O(K + log n) time on average, where K is the number of the elements printed out.
Given a binary search tree T with n elements. For any two keys k1 and k2...
Given a binary search tree T with n elements. For any two keys k1 and k2 such that k1 < k2, there is an algorithm to print all elements x in T such that k1 ≤x ≤k2 in O(K + log n) time on average, where K is the number of the elements printed out.
Why are the most abundant elements found in our bodies not the most abundant elements found...
Why are the most abundant elements found in our bodies not the most abundant elements found in Earth's crust? (e.g., What characteristics of the most abundant elements in our bodies make them suitable for life?) How do the structures of carbohydrates, lipids, proteins (structural and enzymatic), and nucleic acids relate to their functions? Include in your discussion a brief description of the structure of each type of molecule.
Consider a simple economy with search and unemployment. The matching function is given by: M =...
Consider a simple economy with search and unemployment. The matching function is given by: M = em(Q, A) = eQ^(3/5)A^(2/5) where the government supplied employment insurance is b = 0.5, the worker productivity is z = 1.3, firms’ cost of posting a vacancy is k = 0.1, the matching efficiency parameter is e = 0.4191 and the worker’s bargaining power factor is a = 0.5. The working-age population is N = 1000 and we denote by Q the labor force....
Consider the dissociaton of methane, into the elements H2g and C(s) given a) the change of...
Consider the dissociaton of methane, into the elements H2g and C(s) given a) the change of enthalpy of reaction is -74.85 kJ/mol and change of entropyof reaction is -80.67 J/mol K at 298K. Calculate the Keq at 298K. b) Assuming that change in enthalpy of formation is independent of temperature, calculate K at 323K. c) Calculate the degree of dissociation of methane at 298K and Ptotal at 0.01 bar.
(C++) Write a program that prints a table in the following format given a "x" read...
(C++) Write a program that prints a table in the following format given a "x" read from the keyboard. For example, if x is 4, it prints out 0 0 1 1 2 4 3 9 4 16 To avoid mismatch, put 8 white spaces between two numbers.
Given the following array of 8 elements, show the steps to sortthe elements in ascending...
Given the following array of 8 elements, show the steps to sort the elements in ascending order using a radix sort. Fill in each of the following blanks.81   546   677   9   97   12   53   22Adjust with 0s:Buckets for ones digit:Buckets for tens digit:Final Result:
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT