~/problems / Stateful stores / Bank system

Basics: accounts with validated deposits and withdrawals

easy basics ~10 min

Bank-system OAs are mostly about validating first, then changing state. A failed operation must leave everything exactly as it was. Build Accounts with:

  • open(account_id) -> bool: create an account with balance 0. Return False (changing nothing) if the id is already taken.
  • deposit(account_id, amount) -> int | None: add amount and return the new balance.
  • withdraw(account_id, amount) -> int | None: take amount out and return the new balance.
  • balance(account_id) -> int | None: the current balance, or None for an unknown account.

deposit and withdraw return None and change nothing when:

  • the account doesn't exist,
  • amount is not positive (0 or negative),
  • (withdraw only) the balance is less than amount. Withdrawing the whole balance is fine.

Amounts are integers.

a = Accounts()
a.open("ann")          # True
a.open("ann")          # False
a.deposit("ann", 100)  # 100
a.withdraw("ann", 30)  # 70
a.withdraw("ann", 80)  # None: not enough money
a.deposit("ann", -5)   # None: amount must be positive
a.deposit("bob", 10)   # None: no such account
a.balance("ann")       # 70
Show hint

keep a dict account_id -> balance and put every check (in, amount > 0, balance >= amount) before the line that changes the balance.

Topic: Bank system. Accounts, transfers that must be accepted, merges; state machines.

0:00
Ctrl ' run · Ctrl ↵ submit
esc