Contents
- Method bisect.bisect (list, item, start, end )
- bisect.bisect_left (list, item, start, end) method
- The bisect.bisect_right method (list, item, start, end)
- The bisect.insort method (list, item, start, end )
- bisect.insort_left (list, element, start, end) method
- bisect.insort_right (list, item, start, end) method
- Sample Code
- Output
The bisection algorithm is used to find a position in a list where data can be inserted to keep the list sorted. Python has a module called bisect. Using this module, we can use bisect algorithms.
To use this module, we must import it using &
import bisect
There are several business-related operations. This is &
Method bisect.bisect (list, item, start, end )
This method is used to find a position in a sorted list where a number can be placed and the list remains sorted. If the element is already present, it will return the rightmost position where the number can be inserted.
bisect.bisect_left (list, item, start, end) method
This method is similar to the bisect () method. The only difference is that if the element is already present, this method will return the left-most space for inserting data.
The bisect.bisect_right method (list, item, start, end)
This method is completely similar to the bisect () method.
The bisect.insort method (list, item, start, end )
This method is used to get a sorted list after inserting an element at the correct position. If the element is already present, it will be inserted to the far right to keep the list sorted.
bisect.insort_left (list, element, start, end) method
This method is the same, like the insort () method. The only difference is that if an item is already present, it will be inserted at the far left to keep the list sorted.
bisect.insort_right (list, item, start, end) method
This method is completely similar to the insort () method.
Sample Code
import bisect my_list = [11, 25, 36, 47, 56, 69, 69, 69 , 78, 78, 91, 102, 120] print (’Correct Location to insert 53 is:’ + str (bisect.bisect (my_list, 53, 0, len (my_list) ))) print (’Correct right Location to insert 69 is:’ + str (bisect.bisect_right (my_list, 69, 0, len (my_list)))) print (’Correct left Location to insert 69 is:’ + str ( bisect.bisect_left (my_list, 69, 0, len (my_list)))) bisect.insort (my_list, 59, 0, len (my_list)) print (my_list) bisect.insort_left (my_list, 78, 0, len (m y_list )) print (my_list)
Output
Correct Location to insert 53 is: 4 Corr ect right Location to insert 69 is: 8 Correct left Location to insert 69 is: 5 [11, 25, 36, 47, 56, 59, 69, 6 9, 69, 78, 78, 91, 102, 120] [11 , 25, 36, 47, 56, 59, 69, 69, 69, 78, 78, 78, 91, 102, 120]