Thursday, December 5, 2019

bisect module in Python3

The bisect module implements an algorithm for inserting elements into a list while maintaining the list in sorted order.

(1). Inserting in Sorted Order:

Here is a simple example, in which insort( ) is used to insert items into a list in sorted order.



It's output :

The first column of the output shows the new random number. The second column shows the position where the number will be inserted into the list. The remainder of each line is the current sorted list.

Like this, we can manipulate the given data, it might be faster to simply build the list and then sort it once. For long lists, significant time and memory savings can be achieved using this insertion sort algorithm [ i.e, insort( ) ], especially when the operation to compare two members of the list requires expensive computation.

(2). Handling Duplicates:


In the above example the result shown a repeated value, 77. The bisect module provides two ways to handle repeats. New values can be inserted either to the left of existing values, or to the right.
The insort( ) function is actually an alias for insort_right( ), which inserts an item after the existing value. The corresponding function insort_left( ) inserts an item before the existing value.

Let's see an example :


Here is the output :


When the same data is manipulated using bisect_left( ) and insort_left( ), the results are the same sorted list but the insert positions are different for the duplicate values.

=============================================================================

No comments:

Post a Comment