The examples in this paper describe the use of bisect in Python, which is a common practical technique. Share to everyone for your reference. The specific analysis is as follows:
In general, bisect in Python is used to manipulate arrays of sorts, such as when you are inserting data into an array. The following code demonstrates how to do this:
Import Bisectimport randomrandom.seed (1) Print (' New pos contents ') Print ('-----------------') l=[] for I in range (1,15): C0/>r=random.randint (1,100) position=bisect.bisect (l,r) bisect.insort (l,r) print '%3d%3d '% (R, Position), L
The output is:
New Pos Contents----------------- 0 [+] 1 [+], 1 [+, 2, 1] [+] [+ ] [2, +, 26, [+]--[+]-------------------------- , the ten, Ten, [] 0 [Ten, +, +, A, 3, 9, 3, +, and 0 [3], (+), (+), (-) Ten, (+), (+), (+), (+), (+), (+), (+), 4 [3, ten, +, +, 9, +, , 3, 10, 14, 26 , 1 0 [1, 3, 10, 14, 26, 44, 45, 50, 66, 77, 77, 79, 84, 85]----
As you can see, the array is sorted at the same time as these random numbers are inserted. However, there are some repeating elements, such as the above 77, 77. You can set the order of these repeating elements, if you want the repeating element to appear on the left side of the same element as he is using bisect_left, otherwise it is used bisect_right, the corresponding use Insort_left and insort_right. For example, the following code, we can see the duplicate element index changes:
Import Bisectimport randomrandom.seed (1) Print (' New pos contents ') Print ('-----------------') l=[] for I in range (1,15): C0/>r=random.randint (1,100) position=bisect.bisect_left (l,r) bisect.insort_left (l,r) print '%3d%3d ' % (r,position), L
The output is:
New Pos Contents----------------- 0 [+] 1 [+], 1 [+, 2, 1] [+] [+ ] [2, +, 26, [+]-------------------------------------- 0 [Ten, +, +, A, 3, 9, 0 [3, ten, +,-----------------] [3, ten, (+), (4), (+), (+), +, 3, 3, 10, (+), +/--), and 14, 8 ,,,,,,,,,, 10, 14, 26, 44, 45, 50, 66, 77, 1, 0 [1, 3, +, 77, and 79]
This function bisect.bisect (List,key), like the tailmap of TreeMap in Java (Fromkey).
Hopefully this article will help you with Python programming.