Fix the funds transfer step with an external ledger

Review the AI's codeEasy12 minStripe style

Your task

An AI wrote a funds transfer view that debited the source account, called an external ledger over the network, then credited the destination. When the ledger call failed, money left one account and never arrived in the other. Your team now models a batch of transfers so that each one applies whole or not at all.

An assistant wrote apply_transfers_atomically(balances, transfers). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • balances: each account's balance, as integers. The account number is the index.
  • transfers: the transfers in order, each written src,dst,amount,ledger. ledger is the status the external ledger returned for that transfer.
  • Return the balances after every transfer, as a new list.

Rules the tests check:

  • Split a transfer on ,. Skip it unless it has exactly 4 parts. Trim whitespace from both ends of each part.
  • src, dst and amount must each be an integer: an optional - followed by one or more digits 0 to 9. Otherwise skip the transfer.
  • Skip the transfer when src or dst is not a valid account number, when src equals dst, when amount is 0 or less, or when the source's current balance, after the transfers before it, is less than amount.
  • Apply the transfer only when ledger is exactly ok, case included. Any other status means the ledger did not confirm it, so skip it.
  • Applying a transfer moves amount from src to dst. A skipped transfer changes nothing.

Examples

apply_transfers_atomically(balances: list[int], transfers: list[str]) -> list[int]
Example 1
Inputapply_transfers_atomically([100, 50], ["0,1,30,ok"])
Output[70, 80]
Example 2
Inputapply_transfers_atomically([100, 50], ["0,1,30,fail"])
Output[100, 50]
Example 3
Inputapply_transfers_atomically([100, 0, 0], ["0,1,60,ok", "1,2,60,ok"])
Output[40, 0, 60]