Editor

All or Nothing Transfers

#617 · Errors and exceptions · Advanced · 120 XP · about 22 min

A bank runs a batch of transfers as one job: either every transfer happens, or none of them does. Write apply_transfers(balances, transfers), where balances is a dictionary from account name to amount and transfers is a list of (sender, receiver, amount) tuples, done in order.

If every transfer is valid, change balances itself and return it. At the first transfer that is not valid, put every balance back as it was before the batch, in the same dictionary, and raise a ValueError with the message 'transfer N failed: ' followed by the reason. N counts the transfers from 1, and the reason is the first of these that applies:

  • 'unknown account Zed' when the sender is not in balances, and then the same for the receiver.
  • 'amount must be positive' when the amount is 0 or less.
  • 'Ann has 20, needs 50' when the sender's balance at that moment is less than the amount.

Examples

b = {'Ann': 100, 'Bob': 20}
apply_transfers(b, [('Ann', 'Bob', 30), ('Bob', 'Ann', 50)])
# returns {'Ann': 120, 'Bob': 0}

b = {'Ann': 100, 'Bob': 20}
apply_transfers(b, [('Ann', 'Bob', 30), ('Bob', 'Ann', 80)])
# raises ValueError: transfer 2 failed: Bob has 50, needs 80
# and b is {'Ann': 100, 'Bob': 20} again

In the first example Bob has 50 by the time of the second transfer, so it goes through.

Constraints

  • At most 10,000 accounts and 10,000 transfers.
  • Amounts are whole numbers.

Note

The caller holds the same dictionary, so restoring it means changing its contents back. Making a new dictionary inside the function does not change the caller's.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.