Reputation: 63
Can someone please explain me what the bisect_left function from the bisect library actually does? Example:
import bisect
bisect.bisect_left([1,2,3], 2)
This code will print '1'. But what is the rule for this printing? Is '2' inserted in the list, because according to the Python documentation, it should "locate the insertion point for x(in this case 2) in the list to maintain sorted order". Please, maybe someone could provide more examples and could help me to understand! Thank you!
Upvotes: 4
Views: 10927
Reputation: 2737
Starting with bisect
, one use (as shown here) is to find an index into one list that can be used to dereference a related list:
from bisect import bisect
def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):
i = bisect(breakpoints, score)
return grades[i]
grades = [grade(score) for score in [33, 99, 77, 70, 89, 90, 100]]
print(grades)
Output:
['F', 'A', 'C', 'C', 'B', 'A', 'A']
bisect_left
operates the same way as bisect
but in the case of a "tie" it will return the index to the "left" of the match (e.g., a score of 70 in the above example would map to "D" using bisect_left
)
Upvotes: 13
Reputation: 267
Bisect maintains a list in sorted order. If you insert an item into the list, the list still maintains its order.
Since your list is already sorted, bisect.bisect_left([1,2,3], 2) will insert the item 2 after 2 in your list (since the item 2 is already present in list).
You can find more about the "bisect" module here:
https://docs.python.org/3/library/bisect.html
Upvotes: 3