38/40
Part 8 of 8 · Follow-upsLearn and do

Back to the GPU credit ledger

Before you write the ledger, list the tests you'd write for any heap code:

  • Ties at equal priority, with items that can't be compared.
  • An empty heap: heappop raises IndexError.
  • One item, and all items equal.
  • The boundary: a credit that expires at exactly now.
  • Input in descending order, the worst case for pushes.
  • A check against sorted() on random input.

Here are level 1's rules again, from the statement at the start of the lesson:

  • grant(credit_id, amount, start) adds amount credits that count from time start on.
  • spend(amount, timestamp) uses credits at timestamp.
  • balance(timestamp) returns every grant with start <= timestamp, minus every spend at or before timestamp.
  • Calls arrive in any timestamp order. A spend recorded late still counts at its own timestamp.
  • A repeated credit_id, or an amount that isn't positive, raises ValueError and changes nothing.

In the editor, write level 1. CreditLedger records each grant in self.grants and each spend in self.spends, and balance(t) works the answer out from them only when it's asked for.