progress

~/problems / Stateful stores / Bank system

Accounts with validated deposits and withdrawals

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

Bank-system assessments are mostly about validating first, then changing state: a failed operation leaves everything as it was. Build Accounts with:

  • open(account_id) -> bool: create an account with balance 0; False if the id is taken.
  • deposit(account_id, amount) -> int | None and withdraw(account_id, amount) -> int | None: change the balance and return the new one.
  • balance(account_id) -> int | None: the balance, or None for an unknown account.

deposit and withdraw return None and change nothing if the account doesn't exist, amount isn't positive, or (withdraw) the balance is below amount. Withdrawing the whole balance is fine.

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

a dict account_id -> balance, with every check before the line that changes it.

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

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc