23/29
Part 5 of 6 · Snapshots, and a worked exampleLearn and do
A worked example: a ledger in four levels
Here's a small system of our own, built the way this lesson says, with outputs from a real run. The spec:
- Level 1.
deposit(t, acct, amount)returns the new balance.withdraw(t, acct, amount)returns the new balance, orNoneif the account holds less thanamount, and then nothing changes. Amounts are positive, and times increase from call to call. - Level 2.
top(t, n)returns thenlargest balances as(acct, balance)pairs, ties broken by account name. - Level 3.
balance_at(acct, t)returns the balance after every operation at or beforet, orNoneif the account had no balance yet. - Level 4.
rollback(t)undoes every operation aftert.
Levels 1 and 2: one balance per account
class Ledger:
def __init__(self) -> None:
# acct -> balance
self._balances: dict[str, int] = {}
def deposit(self, t: int, acct: str, amount: int) -> int:
self._balances[acct] = self._balances.get(acct, 0) + amount
return self._balances[acct]
def withdraw(self, t: int, acct: str, amount: int) -> int | None:
if self._balances.get(acct, 0) < amount:
return None
self._balances[acct] -= amount
return self._balances[acct]
def top(self, t: int, n: int) -> list[tuple[str, int]]:
return sorted(self._balances.items(), key=lambda row: (-row[1], row[0]))[:n]
Before you read on: ana holds 80 and calls withdraw(4, "ana", 100). What comes back?
ana, ben and cy each hold 50 at time 6. What does top(6, 3) return?
Pick an answer above to see the rest