1
+ # YouTube Video: https://www.youtube.com/watch?v=mqaf7vj1AdA&list=PL5tcWHG-UPH1kjiE-Fqt1xCSkcwyfn2Jb
2
+ """
3
+ Bisect:
4
+ -"Built-in" binary search method in Python.
5
+ -Can be used to search for an element in a sorted list.
6
+ """
7
+
8
+ # Import allows us to make use of the bisect module.
9
+ import bisect
10
+
11
+ # This sorted list will be used throughout this video
12
+ # to showcase the functionality of the "bisect" method.
13
+ A = [- 14 , - 10 , 2 , 108 , 108 , 243 , 285 , 285 , 285 , 401 ]
14
+
15
+ # The bisect_left function finds index of the target element.
16
+ # In the event where there are duplicate entries satisfying the target
17
+ # element, the bisect_left function returns the left-most occurrence.
18
+
19
+ # -10 is at index 1
20
+ print (bisect .bisect_left (A , - 10 ))
21
+
22
+ # First occurrence of 285 is at index 6
23
+ print (bisect .bisect_left (A , 285 ))
24
+
25
+ # The bisect_right function returns the insertion point which comes after,
26
+ # or to the right of, any existing entries in the list.
27
+
28
+ # Index position to right of -10 is 2.
29
+ print (bisect .bisect_right (A , - 10 ))
30
+
31
+ # Index position after last occurrence of 285 is 9.
32
+ print (bisect .bisect_right (A , 285 ))
33
+
34
+ # There is also just a regular default "bisect" function. This function
35
+ # is equivalent to "bisect_right":
36
+
37
+ # Index position to right of -10 is 2. (Same as bisect_right)
38
+ print (bisect .bisect (A , - 10 ))
39
+
40
+ # Index position after last occurrence of 285 is 9. (Same as bisect_right).
41
+ print (bisect .bisect (A , 285 ))
42
+
43
+ # Given that the list A is sorted, it is possible to insert elements into
44
+ # A such that the list remains sorted. Functions "insort_left" and
45
+ # "insort_right" behave in a similar way to "bisect_left" and "bisect_right",
46
+ # only the insort functions insert at the index positions.
47
+ print (A )
48
+ bisect .insort_left (A , 108 )
49
+ print (A )
50
+
51
+ bisect .insort_right (A , 108 )
52
+ print (A )
0 commit comments