bisect and functools: find the spot, pre-fill, fold
🌍 In real life. To find a word in a dictionary you don't read from page one. You open the middle, see you've gone too far, open the middle of the first half, and so on. In a few jumps you're there.
bisect does that on a sorted list: it finds where a value belongs by checking the middle and throwing half away each time. Step by step:
bisect.bisect_left(a, x): the leftmost spot forx(before any equal items); it's also how many items are smaller thanxbisect.bisect_right(a, x)(or justbisect.bisect): the rightmost spot (after any equal items); how many are no bigger thanxbisect.insort(a, x): putsxinto that spot, so the list stays sorted- a list of a million items needs only about 20 looks
The idea in one sentence: bisect finds where a value belongs in a sorted list by halving the search each step, and functools adds tools for functions: partial pre-fills arguments and reduce folds a list into one value.
Its words:
- binary search: check the middle, throw away the half that can't hold the answer, repeat
bisect_left(a, x)/bisect_right(a, x): the first or last place x can goinsort(a, x): put x in its sorted placepartial(f, rate=18): a new function with some arguments filled in
Watch the search. The class's exam marks are on a shelf, smallest to biggest. The lo and hi markers hold the part of the shelf still in play; the middle book lifts, Python's comparison floats above it, and one marker jumps past it. Notice how bisect_left and bisect_right stop on different sides of the two 55s.
import bisect
def grade(score: int) -> str:
cutoffs = [60, 70, 80, 90]
return "FDCBA"[bisect.bisect(cutoffs, score)]
for score in [45, 60, 79, 80, 97]:
print(score, grade(score))
times = [48, 52, 61]
bisect.insort(times, 55)
print(times)functools: two more tools for functions.
partial(func, ...)makes a new function with some arguments already filled in. In India many bills, like a phone bill or a gym membership, add 18% GST, so instead of writingrate=18every time, makewith_gst = partial(add_tax, rate=18)once.reduce(func, items, start)folds a list into one value: it combines the start with the first item, that answer with the next item, and so on. Always give a start value: without one, an empty list raisesTypeError.
from functools import partial, reduce
def add_tax(price: int, rate: int) -> int:
return price + price * rate // 100
with_gst = partial(add_tax, rate=18)
print(with_gst(200), "rupees")
bill = [200, 150, 90]
print(reduce(lambda total, p: total + with_gst(p), bill, 0), "rupees")
print(reduce(lambda a, b: a * b, [2, 3, 4], 1))
print(reduce(lambda a, b: a * b, [], 1))What it costs. Each step of a binary search halves what's left, so a sorted list of 1,000,000 items needs about 20 checks, where walking from the front could need a million. insort finds the spot that fast, but then shifts the items after it, like list.insert.
Mistakes and edge cases.
- An unsorted list.
bisect.bisect([5, 1, 3], 2)gives 2 without any error, and the answer is meaningless. Sort first. - left or right with ties. For a value already in the list,
bisect_leftgives the spot before the equal items andbisect_rightthe spot after. - reduce of nothing.
reduce(add, [])givesTypeError: reduce() of empty iterable with no initial value; pass a start value.
Quiz
What does this print?
import bisect a = [1, 3, 3, 5] print(bisect.bisect_left(a, 3), bisect.bisect_right(a, 3))What does this print?
import bisect a = [10, 20, 30] bisect.insort(a, 25) print(a)What does this print?
from functools import reduce print(reduce(lambda a, b: a * b, [2, 3, 4], 1))What does this print?
from functools import partial def power(base, exp): return base ** exp square = partial(power, exp=2) print(square(7))bisect gives correct answers only when the list is...
- sorted
- short
- made of strings
The marks must stay in order for bisect to work. Which line breaks that?
import bisect marks = [40, 55, 70, 85] marks.append(60) print(bisect.bisect_left(marks, 75))
Coding tasks
Write
grade(score: int) -> strwithbisect: below 60 is"F", 60–69"D", 70–79"C", 80–89"B", 90 and up"A".A race board keeps finishing times sorted, fastest first. Write
add_time(board: list[int], time: int) -> int: inserttimewithbisectso the board stays sorted (a tie goes after the earlier runner), and give back the runner's place (1 for first).add_tax(price, rate)is written for you. Makewith_gstwithpartial(rate 18), then writebill_total(prices: list[int]) -> intwithreduce: the total of every price with GST added. An empty bill is 0.