Fix the money transfer between two account balances
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:
amountis greater than 0.- Both indices are between 0 and the length of
balancesminus 1. - The two indices are different.
- The source balance is at least
amount. Moving the whole balance is allowed.
- A valid transfer subtracts
amountfrom 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
balancesreturns an empty list.
Examples
apply_transfer(balances: list[int], source_index: int, target_index: int, amount: int) -> list[int]Example 1
Input
apply_transfer([1000, 500], 0, 1, 100)Output
[900, 600]Example 2
Input
apply_transfer([1000, 500], 0, 1, 5000)Output
[1000, 500]Example 3
Input
apply_transfer([1000, 500], 0, 0, 100)Output
[1000, 500]