📜  python bisect - Python (1)

📅  最后修改于: 2023-12-03 15:33:58.258000             🧑  作者: Mango

Python Bisect

Bisect module in Python provides support for binary search algorithm. It provides the functions to insert and search for an item in a sorted list. Bisect is optimized for calculating the position of newly inserted elements in a sorted list of items.

Example usage:

import bisect

sorted_list = [1, 2, 3, 4, 5]
print(bisect.bisect_left(sorted_list, 3))

Output:

2

Here bisect function returns the index of the position where the element 3 should be inserted in the sorted_list. The result is always the leftmost index. If we combine this function with slicing, we can use it for searching items in a range of values.

import bisect

sorted_list = [1, 2, 3, 4, 5]
print(sorted_list[bisect.bisect_left(sorted_list, 2):bisect.bisect_right(sorted_list, 4)])

Output:

[2, 3]

In the above example, we use bisect_left to find the leftmost position where 2 should be inserted and bisect_right to find the rightmost position of 4, both in the sorted_list. Then we use slicing to select the subsequence of items between those indices.

Bisect also provides other functions like :

  • bisect_right(a, x, lo=0, hi=len(a))
  • bisect_left(a, x, lo=0, hi=len(a))
  • insort_right(a, x, lo=0, hi=len(a))
  • insort_left(a, x, lo=0, hi=len(a))

We can use bisect_right to insert an element to the right of the position of already existing elements in the sorted_list.

import bisect

sorted_list = [1, 2, 3, 4, 5]
bisect.insort_right(sorted_list, 6)
print(sorted_list)

Output:

[1, 2, 3, 4, 5, 6]

Bisect_left, the leftmost similar function of bisect_right, looks for the leftmost position to insert the given element, If it already exists in the sorted_list.

With bisect module, we can optimize the insertion of new elements into a sorted list.

import bisect

sorted_list = [1, 2, 3, 4, 5, 6]
bisect.insort_right(sorted_list, 5)
print(sorted_list)

Output:

[1, 2, 3, 4, 5, 5, 6]

We see from the output, insort_right function inserted the element 5 to the right of the rightmost index of first appearance of 5 in the sorted_list.

In conclusion, the Bisect module of python provides efficient binary search functionality along with the methods to insert and search an item in a sorted list. This can be used to optimize code for inserting new elements into a pre-sorted list or finding/fetching items within a given range of values.