An example of bisect module usage in python
- 2020-04-02 14:06:53
- OfStack
This article illustrates the usage of bisect module in python, and shares it with you for your reference.
Specific methods are analyzed as follows:
This module has only a few functions, so once you decide to use binary search, you should immediately think of using this module.
The sample code is as follows:
import bisect
L = [1,3,3,6,8,12,15]
x = 3
x_insert_point = bisect.bisect_left(L,x)# in L Look for x . x Return on existence x On the left, x There is no place to return where it should be inserted .. This is a 3 Exists in the list, returning 1 to the left
print x_insert_point
x_insert_point = bisect.bisect_right(L,x)# in L Look for x . x Return on existence x On the right, x There is no place to return where it should be inserted .. This is a 3 Exists in the list and returns position 3 to the right
print x_insert_point
x_insort_left = bisect.insort_left(L,x)# will x Insert into the list L , x It's inserted on the left
print L
x_insort_rigth = bisect.insort_right(L,x)# will x Insert into the list L , x It's inserted on the right hand side
print L
The test environment for this example is Python2.7.6
The results of the sample run are as follows:
1
3
[1, 3, 3, 3, 6, 8, 12, 15]
[1, 3, 3, 3, 3, 6, 8, 12, 15]
In practice, bisect.insort_left and bisect.insort_right have little difference, and their functions are basically the same.
I hope that this article has helped you to learn Python programming.