The before code pays each debt individually, causing many transactions. The after code calculates net balances per person, then matches debtors and creditors to minimize payments, reducing the total transactions.
### Before: naive approach - pay each debt separately
def naive_settlement(debts):
payments = []
for debtor, creditor, amount in debts:
payments.append((debtor, creditor, amount))
return payments
### After: simplified debts algorithm - minimize transactions
def simplify_debts(debts):
from collections import defaultdict
net_balance = defaultdict(int)
for debtor, creditor, amount in debts:
net_balance[debtor] -= amount
net_balance[creditor] += amount
debtors = []
creditors = []
for person, balance in net_balance.items():
if balance < 0:
debtors.append([person, -balance]) # owes money
elif balance > 0:
creditors.append([person, balance]) # to receive money
payments = []
i, j = 0, 0
while i < len(debtors) and j < len(creditors):
debtor, debt_amount = debtors[i]
creditor, credit_amount = creditors[j]
settled_amount = min(debt_amount, credit_amount)
payments.append((debtor, creditor, settled_amount))
debtors[i][1] -= settled_amount
creditors[j][1] -= settled_amount
if debtors[i][1] == 0:
i += 1
if creditors[j][1] == 0:
j += 1
return payments