Fix the money transfer between two account balances

Review the AI's codeEasy10 min

Your task

You asked an agent for thorough tests of a bank transfer, and it wrote six copies of one happy path: move 100, check both balances. The team now wants the transfer rules in one function, so every edge case can be tested directly.

An assistant wrote apply_transfer(balances, source_index, target_index, amount). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • balances: each account's balance in cents, as integers. The list can be empty.
  • source_index: the position of the account that pays. It can be negative or past the end.
  • target_index: the position of the account that receives. It can be negative or past the end.
  • amount: the amount to move, in cents, an integer. It can be 0 or negative.
  • Return a new list with every balance after the transfer.

Rules the tests check:

  • A transfer is valid only when all of these hold:
    • amount is greater than 0.
    • Both indices are between 0 and the length of balances minus 1.
    • The two indices are different.
    • The source balance is at least amount. Moving the whole balance is allowed.
  • A valid transfer subtracts amount from the source and adds it to the target. Every other balance stays the same.
  • An invalid transfer changes nothing. Return the balances exactly as they were.
  • An empty balances returns an empty list.

Examples

apply_transfer(balances: list[int], source_index: int, target_index: int, amount: int) -> list[int]
Example 1
Inputapply_transfer([1000, 500], 0, 1, 100)
Output[900, 600]
Example 2
Inputapply_transfer([1000, 500], 0, 1, 5000)
Output[1000, 500]
Example 3
Inputapply_transfer([1000, 500], 0, 0, 100)
Output[1000, 500]