8/29
Part 2 of 6 · Data model and one pathLearn and do

A question about the past needs a history

Take the bank, the third system in this lesson and its worked example at the end: deposits and withdrawals arrive with a time, and a later level asks for an account's balance at any time t. When a level asks about the past like that, one current value can't answer. Keep a history instead: a list of (time, value) pairs per key, added to as calls arrive.

# acct -> [(t, balance after the change at t), ...], oldest first
self._history = {}

Here is one account after a deposit of 80 at time 2 and a withdrawal of 30 at time 5:

self._history["ana"], and the balance at tInteractive
balance_at(4) is 80: the entry from time 2, the latest at or before 4. 1 later entry is skipped.

When times only increase, appending keeps every list sorted. That's what makes a question about time t cheap to answer. The worked example below makes this switch at level 3.

In the editor, write the ledger's deposit so that each change adds a (time, balance) pair to the account's history.