Python 3D Academyবাংলা

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:

  1. bisect.bisect_left(a, x): the leftmost spot for x (before any equal items); it's also how many items are smaller than x
  2. bisect.bisect_right(a, x) (or just bisect.bisect): the rightmost spot (after any equal items); how many are no bigger than x
  3. bisect.insort(a, x): puts x into that spot, so the list stays sorted
  4. 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 go
  • insort(a, x): put x in its sorted place
  • partial(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)
bisect(cutoffs, 80) counts the cutoffs that are no bigger than 80: three of them (60, 70, 80), and "FDCBA"[3] is "B". An 80 earns the B.

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 writing rate=18 every time, make with_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 raises TypeError.
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))
The bill folds up as 0 → 236 → 413 → 519. With a start value of 1, multiplying an empty list gives 1 instead of an error.

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_left gives the spot before the equal items and bisect_right the spot after.
  • reduce of nothing. reduce(add, []) gives TypeError: reduce() of empty iterable with no initial value; pass a start value.

Quiz

  1. What does this print?

    import bisect
    
    a = [1, 3, 3, 5]
    print(bisect.bisect_left(a, 3), bisect.bisect_right(a, 3))
  2. What does this print?

    import bisect
    
    a = [10, 20, 30]
    bisect.insort(a, 25)
    print(a)
  3. What does this print?

    from functools import reduce
    
    print(reduce(lambda a, b: a * b, [2, 3, 4], 1))
  4. What does this print?

    from functools import partial
    
    def power(base, exp):
        return base ** exp
    
    square = partial(power, exp=2)
    print(square(7))
  5. bisect gives correct answers only when the list is...

    • sorted
    • short
    • made of strings
  6. 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

  1. Write grade(score: int) -> str with bisect: below 60 is "F", 60–69 "D", 70–79 "C", 80–89 "B", 90 and up "A".

  2. A race board keeps finishing times sorted, fastest first. Write add_time(board: list[int], time: int) -> int: insert time with bisect so the board stays sorted (a tie goes after the earlier runner), and give back the runner's place (1 for first).

  3. add_tax(price, rate) is written for you. Make with_gst with partial (rate 18), then write bill_total(prices: list[int]) -> int with reduce: the total of every price with GST added. An empty bill is 0.