TIL - The bisect Module Gives You Logarithmic Inserts Into a Sorted List
Maintaining a sorted list with list.sort() after every insert is O(n log n). bisect finds the right position in O(log n) and insort drops the element in for you.
import bisect
scores = [10, 20, 30, 40, 50]
# Find insertion point without inserting
pos = bisect.bisect_left(scores, 35)
print(pos) # 3
# Insert and keep sorted
bisect.insort(scores, 35)
print(scores) # [10, 20, 30, 35, 40, 50]
# Practical: map a score to a grade band
breakpoints = [60, 70, 80, 90]
grades = ["F", "D", "C", "B", "A"]
def grade(score):
return grades[bisect.bisect(breakpoints, score)]
print(grade(85)) # B
print(grade(92)) # A
bisect_left vs bisect_right controls whether equal values land to the left or right of existing matches.