This article mainly introduces the usage examples of the bisect module in python, and introduces the usage of several common functions in the bisect module in the form of examples, which is of great practical value, for more information about how to use the bisect module in python, see the following example.
The specific method is analyzed as follows:
This module has only a few functions. Once you decide to use a binary search, you need to use this module immediately.
The sample code is as follows:
Import bisectL = [1, 3, 6, 8, 12, 15] x = 3x_insert_point = bisect. bisect_left (L, x) # search for x in L. If x exists, the position on the left of x is returned. If x does not exist, the position to be inserted is returned .. this is 3 that exists in the list and returns the position 1 print x_insert_pointx_insert_point = bisect on the left. bisect_right (L, x) # search for x in L. If x exists, the position on the right of x is returned. If x does not exist, the position to be inserted is returned .. this is where 3 exists in the list and returns the right position 3 print x_insert_pointx_insort_left = bisect. insort_left (L, x) # insert x to list L. If x exists, insert it to print lx_insort_ri1_= bisect on the left. insort_right (L, x) # insert x to list L. If x exists, insert it to print L on the right.
In this example, the test environment is Python2.7.6.
The running result is as follows:
13 [1, 3, 3, 3, 6, 8, 12, 15] [1, 3, 3, 3, 3, 6, 8, 12, 15]
In actual use, the difference between bisect. insort_left and bisect. insort_right is not big, and their functions are basically the same.
I hope this article will help you learn Python programming.