Library contents

Python bisect_left and bisect_right

bisect_left finds the first insertion position for a value, and bisect_right finds the position after its equals. Their difference counts matches.

A simple example

bisect_left and bisect_right

  1. Start with Sorted values 1, 2, 2, 3
  2. Do this Find left and right insertion positions for 2
  3. Result 1 and 3
The two matching elements occupy zero-based indices 1 and 2. Their count is 3 minus 1.

Syntax

Python syntax
bisect_right(prices, target) - bisect_left(prices, target)
Run this example in Python

Save the program as lesson.py. Use Python 3.9 or later.

python3 lesson.py

Count equal prices in a sorted catalog

A price catalog is already sorted and can contain repeated thresholds. Locate the correct boundary and check what the returned position means when an exact value is absent.

From the programprices = [10, 20, 20, 40]
First output line20 2
lesson.py
from bisect import bisect_left, bisect_right

prices = [10, 20, 20, 40]
for target in (20, 25):
    print(target, bisect_right(prices, target) - bisect_left(prices, target))
Output
20 2
25 0

The input must remain sorted. For a missing value both boundaries are equal, so the same calculation also handles a miss.

Python documentation for bisect_left and bisect_right

Advertisements

Locate a numbered tote

A parcel clerk keeps tote numbers in ascending order. Find the specified item in the sorted register. How many smaller entries come before it?

Given4 · 9 · 15 · 22 | seek 15
Worked result2

Find the earliest permit

A permit clerk starts with the smallest valid identifier. Find the specified item in the sorted register. How many smaller entries come before it?

Given3 · 6 · 10 | seek 3
Worked result0