Fix the funds transfer step with an external ledger
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 writtensrc,dst,amount,ledger.ledgeris 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,dstandamountmust each be an integer: an optional-followed by one or more digits 0 to 9. Otherwise skip the transfer.- Skip the transfer when
srcordstis not a valid account number, whensrcequalsdst, whenamountis 0 or less, or when the source's current balance, after the transfers before it, is less thanamount. - Apply the transfer only when
ledgeris exactlyok, case included. Any other status means the ledger did not confirm it, so skip it. - Applying a transfer moves
amountfromsrctodst. A skipped transfer changes nothing.
Examples
apply_transfers_atomically(balances: list[int], transfers: list[str]) -> list[int]Example 1
Input
apply_transfers_atomically([100, 50], ["0,1,30,ok"])Output
[70, 80]Example 2
Input
apply_transfers_atomically([100, 50], ["0,1,30,fail"])Output
[100, 50]Example 3
Input
apply_transfers_atomically([100, 0, 0], ["0,1,60,ok", "1,2,60,ok"])Output
[40, 0, 60]