1 Example
This module has only a few functions,
Once you decide to use a binary search, you immediately think of using this module
Import bisect L = [1,3,3,6,8,12,15] x = 3 x_insert_point = Bisect.bisect_left (l,x) #在L中查找x, X is present and returns to the left of X, X does not exist where the return should be inserted ... This is 3 present in the list, return to the left position 1 print x_insert_point x_insert_point = bisect.bisect_right (l,x) #在L中查找x, X is present when it returns to the right position of X , X does not exist where the return should be inserted ... This is 3 present in the list, return to the right position 3 print x_insert_point x_insort_left = Bisect.insort_left (l,x) #将x插入到列表L中, X exists when inserted on the left side print L x_insort_rigth = bisect.insort_right (l,x) #将x插入到列表L中, X is present when inserted on the right print L
Results:
1
3
[1, 3, 3, 3, 6, 8, 12, 15]
[1, 3, 3, 3, 3, 6, 8, 12, 15]
Actually in use
2 The functions provided by the Bisect module bisect module are: (1) Find Bisect.bisect_left (a,x, Lo=0, Hi=len (a)): Find the index of x inserted in the ordered list A. Lo and hi are used to specify the interval for the list, and the entire list is used by default. Bisect.bisect_right (A,x, Lo=0, Hi=len (a)) Bisect.bisect (A, x,lo=0, Hi=len (a)) These 2 are similar to Bisect_left, but if x already exists, insert it to the right. (2) Insert Bisect.insort_left (a,x, Lo=0, Hi=len (a)) to insert X in ordered list A. If x already exists, insert it to the left. The return value is index. and A.insert (Bisect.bisect_left (a,x, lo, HI), x) have the same effect. Bisect.insort_right (A,x, Lo=0, Hi=len (a)) Bisect.insort (A, x,lo=0, Hi=len (a)) and insort_left are similar, but if x already exists, insert it to the right. Can function can be divided into 2 classes, bisect*, used to find index. Insort* is used for actual insertion. The default repetition is inserted from the right. The actual commonly used estimate is insort.