Last active
February 17, 2026 02:32
-
-
Save izakp/3f2a409476b30028cc8fc2b6de3ac7ea to your computer and use it in GitHub Desktop.
Split a check
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import sys | |
| def split_check(*args): | |
| """ | |
| split_check(('josh', 50), ('jake', 100), ('isac', 100)) | |
| """ | |
| total = 0 | |
| for name, amount in args: | |
| total += amount | |
| avg = total / len(args) | |
| print(f"Average: {round(avg, 2)}") | |
| recipients = {} | |
| payers = {} | |
| # Split into who overpaid and who underpaid | |
| for name, amount in args: | |
| diff = amount - avg | |
| if diff > 0: | |
| recipients[name] = { | |
| 'diff': diff, | |
| 'payments': 0 | |
| } | |
| else: | |
| payers[name] = diff | |
| # Calculate total amount owed to all recipients | |
| total_recipients_owed = 0 | |
| for name, adjustment in recipients.items(): | |
| total_recipients_owed += adjustment['diff'] | |
| # Calaculate the percentage of total due to each recipient | |
| for name, adjustment in recipients.items(): | |
| percentage = adjustment['diff'] / total_recipients_owed | |
| recipients[name]['percentage'] = percentage | |
| # For each payer, pay the percentage of the amount owed to reach the average, to each recipient | |
| output = [] | |
| for name, amount in payers.items(): | |
| for receipient_name, adjustment in recipients.items(): | |
| payment = amount * adjustment['percentage'] * -1 | |
| recipients[receipient_name]['payments'] += payment | |
| if payment != 0: | |
| output.append(f"{name} pays {receipient_name} {round(payment, 2)}") | |
| # Check the math! | |
| for receipient_name, adjustment in recipients.items(): | |
| if round(adjustment['diff'], 2) != round(adjustment['payments'], 2): | |
| print(f"Adjustment error! Not all totals add up. {adjustment}") | |
| print(recipients) | |
| sys.exit(1) | |
| for line in output: | |
| print(line) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment