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 balance0. ReturnFalse(changing nothing) if the id is already taken.deposit(account_id, amount) -> int | None: addamountand return the new balance.withdraw(account_id, amount) -> int | None: takeamountout and return the new balance.balance(account_id) -> int | None: the current balance, orNonefor an unknown account.
deposit and withdraw return None and change nothing when:
- the account doesn't exist,
amountis not positive (0or 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.