Trending

World technology news

→
Keeping today’s rate off yesterday’s order with Python’s bisect
Software Engineering · 2026
Software Engineering

Keeping today’s rate off yesterday’s order with Python’s bisect

A tested example with two prices and four order dates handles equality on a changeover day, orders before the first rate and conflicting start dates.

Developer's JournalPublished: Dec 2, 20266 min read
Reading progress0%
In this article
  1. A small error at a monthly boundary
  2. Representing intervals without an end date in each row
  3. Why equality belongs on the right
  4. Checking the four answers by hand
  5. Where the business date comes from
  6. Paying for the sort once

A small error at a monthly boundary

A workshop charges a fixed handling fee per box received. The fee changes from 12.00 units in November to 14.50 on the first day of December. An accountant finishes entering a November delivery in December. Which rate belongs on the order? In this example the business rule specifies the date of receipt. The entry date, the time the report is rerun and the most recent price on a screen are different pieces of information. Our function therefore takes the order’s business date and a table of dated rates. It returns one price or reports that no rate exists for that day. The amounts are fictional and deliberately easy to check by hand. The example runs locally with the Python standard library.

Representing intervals without an end date in each row

Store the start of each rate. The November row applies from November 1 up to, but excluding, December 1. The December row includes its start day. Adding a new row now establishes the prior row’s end without a second edit. The final interval is open. A contract with an explicit end or a deliberate gap would need an additional rule. Here the open end means only that the last known rate applies until superseded. The sample deliberately supplies December before November. The constructor parses and sorts the dates, then stores dates and corresponding prices in immutable tuples. Lookups reuse that one sorted date sequence rather than reconstructing it on every order.

Application flowConceptual sketch · summary of the article's technical flow

Why equality belongs on the right

Python’s bisect_right returns the insertion point to the right of equal values. We need not insert anything. Subtracting one from that position identifies the last start date less than or equal to the order date. An order on November 30 falls between two starts. On December 1 the choice of side selects the December row. Using the left insertion point with the same subtraction would apply the previous rate on the first day of the new one. Another trap is Python’s negative indexing. Without the explicit lower-bound check, an October order would silently receive the last price in the table. Testing a mid-month order alone would reveal neither mistake.

from bisect import bisect_right
from datetime import date
from decimal import Decimal

def make_table(entries):
    rows = sorted((date.fromisoformat(day), Decimal(price)) for day, price in entries)
    dates = tuple(day for day, _ in rows)
    if not dates or len(set(dates)) != len(dates):
        raise ValueError("empty or duplicate start date")
    return dates, tuple(price for _, price in rows)

def price_on(table, iso_day):
    dates, prices = table
    i = bisect_right(dates, date.fromisoformat(iso_day)) - 1
    if i < 0:
        raise LookupError("no active rate")
    return prices[i]

table = make_table([("2026-12-01", "14.50"), ("2026-11-01", "12.00")])
for day in ("2026-10-31", "2026-11-30", "2026-12-01", "2026-12-07"):
    try:
        value = price_on(table, day)
    except LookupError:
        value = "no active rate"
    print(day, value)
assert price_on(table, "2026-12-01") == Decimal("14.50")
try:
    make_table([("2026-12-01", "10"), ("2026-12-01", "11")])
except ValueError:
    print("duplicate rejected")
else:
    raise AssertionError("duplicate accepted")

# Expected output
# 2026-10-31 no active rate
# 2026-11-30 12.00
# 2026-12-01 14.50
# 2026-12-07 14.50
# duplicate rejected

Checking the four answers by hand

October 31 has no active rate. November 30 returns 12.00, December 1 returns 14.50 and December 7 also returns 14.50. Passing strings to Decimal avoids introducing a binary floating-point conversion into this example. The function does no rounding, tax calculation or currency conversion. Its job is to select a record. After printing the four cases an assertion fixes the expected result for the changeover date. The last test supplies two different amounts with the same start. Table construction rejects the conflict instead of quietly preferring one row. If identical duplicates should be accepted in another business, make that an explicit input rule and test it separately.

Where the business date comes from

The sample accepts a business date rather than a timestamp. A delivery just after midnight in Istanbul may appear under the previous date in a raw record using another time zone. A perfectly implemented binary search will still return the wrong price if its caller cuts the wrong date from that timestamp. Agree on the relevant location or shift boundary, derive the business date accordingly and pass that value to the lookup. A retroactive correction poses a separate question. If a rate entered today is effective from last week, should issued invoices be recalculated? That is a business decision. Saving the applied rate or version with an issued invoice can make the historical answer reproducible.

Paying for the sort once

Building the rate table requires sorting its rows. Each subsequent lookup uses binary search rather than a fresh scan. The distinction matters when many orders share the same rate table. Sorting again before every query would largely undo the benefit. On a change, building and validating a new pair of tuples before using it reduces the risk of mixing dates from one version with prices from another. A multi-product system would need its own ordered sequence for each applicable product and currency. A final business check makes the boundary tangible. Ten boxes received on November 30 and ten on December 1 cost 265.00 units together. Charging the December rate for both would produce 290.00.

Be the first reader ✎ Write a comment

Reader discussion

Discussion prompt

Which alternative architecture would you try for the same problem?

No comments yet. Be the first to contribute.

Write a comment

Comments are real visitor contributions. Repeated, link-heavy or abusive submissions may be limited.