Cover Image for Bisect Module in Python
140 views

Bisect Module in Python

The bisect module in Python is a built-in module that provides functions for binary search and insertion into sorted sequences. It allows you to efficiently search for an element in a sorted list or insert an element into a sorted list while maintaining the list’s sorted order. The bisect module is particularly useful when dealing with large datasets or when you need to perform fast lookups or insertions into sorted collections.

Here are some key functions and classes provided by the bisect module:

  1. bisect_left(a, x, lo=0, hi=len(a)): This function finds the index where an element x should be inserted into a sorted sequence a to maintain the sorted order. It returns the leftmost insertion point. If the element is already present, it returns the index of the leftmost occurrence.
  2. bisect_right(a, x, lo=0, hi=len(a)): Similar to bisect_left, this function finds the rightmost insertion point for element x in the sorted sequence a. It returns the index where the element should be inserted to maintain the sorted order.
  3. insort_left(a, x, lo=0, hi=len(a)): This function inserts element x into the sorted sequence a while maintaining the sorted order. It is equivalent to calling a.insert(bisect_left(a, x, lo, hi), x).
  4. insort_right(a, x, lo=0, hi=len(a)): Similar to insort_left, this function inserts element x into the sorted sequence a at the rightmost insertion point to maintain the sorted order.

Here’s an example of using the bisect module to perform binary search and insertion into a sorted list:

Python
import bisect

# Sorted list
sorted_list = [1, 3, 5, 7, 9]

# Perform binary search
index = bisect.bisect_left(sorted_list, 5)
if sorted_list[index] == 5:
    print(f"Element 5 found at index {index}")
else:
    print("Element 5 not found in the list")

# Insert element into the sorted list
bisect.insort_left(sorted_list, 6)
print("Sorted list after inserting 6:", sorted_list)

This example, we use bisect_left to find the leftmost insertion point for the element 5 in the sorted list. We then check if the element is already present. Next, we use insort_left to insert the element 6 into the sorted list while maintaining its sorted order.

The bisect module is a handy tool for efficiently working with sorted sequences, and it can be particularly useful in various algorithms and data manipulation tasks.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS