Advertisement
Iam_Sandeep

Binary Search using bisect Three methods

Jul 2nd, 2022
812
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.66 KB | None
  1. #User function template for Python
  2. #Method 1
  3. from bisect import bisect_left as bs
  4. class Solution:
  5.     def binarysearch(self, a, n, k):
  6.         idx=bs(arr,k)
  7.         if idx<n and a[idx]==k:
  8.             return idx
  9.         else:return -1
  10.        
  11. #Method 2
  12. from bisect import bisect_right as bs
  13. class Solution:
  14.     def binarysearch(self, a, n, k):
  15.         idx=bs(arr,k)
  16.         if idx<n and a[idx]==k:
  17.             return idx
  18.         if idx>1 and a[idx-1]==k:
  19.             return idx-1
  20.         return -1
  21.    
  22. #Method 3
  23. from bisect import bisect_left as bl,bisect_right as br
  24. class Solution:
  25.     def binarysearch(self, a, n, k):
  26.         x,y=bl(a,k),br(a,k)
  27.         if x==y:return -1
  28.         else:
  29.             return x
  30.  
Advertisement
RAW Paste Data Copied
Advertisement