Introduction
Splitting bills on a trip is surprisingly tricky: different people pay for different things, shared between different people. This program keeps money in paise to avoid rounding errors and finds a short list of payments that settles everything.
Problem statement
Objectives
- Avoid floating-point errors by storing money as integers
- Model a group with a class and expenses with a dataclass
- Write a greedy settlement algorithm
- Parse simple English-like commands
Features
- Exact sharing in paise with leftover paise distributed
- Split among everyone or chosen people (case-insensitive names)
- Balances that always sum to zero
- Greedy settlement: biggest debtor pays biggest creditor
- Validation of names and amounts
Concepts demonstrated
- Integer money arithmetic
- Classes and methods
- Greedy algorithms
- Command parsing
System architecture
Group holds the people and a list of Expense records. add splits an amount with divmod, giving any leftover paise to the first members so shares add up exactly. balances adds what each person paid and subtracts their shares. settlements repeatedly matches the largest debtor with the largest creditor until everyone is settled. handle parses one command and delegates to the group.
Folder structure
Complete source code
main.py
What each file does
- main.py
- The whole program: data classes, validation, the command loop and the report.
How to run it
Run
Test against the expected output
Expected output
Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.
balances people Asha Ravi Meera Kiran Asha paid 1200 for dinner split all Ravi paid 600 for cab split Ravi Meera Meera paid 450.50 for snacks Kiran paid 100 for tea split asha kiran Sana paid 300 for movie Asha paid -50 for nothing Ravi paid lots for gifts balances settle quit
Testing
- Run
python main.py < tests/sample-input.txtand compare withtests/expected-output.txt. - ₹450.50 split four ways gives two shares of ₹112.63 and two of ₹112.62.
- Sana is not in the group, -50 and 'lots' are rejected.
- Asha is owed ₹737.37, exactly what Ravi, Meera and Kiran owe together, and three payments settle the trip.
Common errors
Shares like 112.625 that don't add up
Store amounts in paise (integers) and spread the remainder from divmod.
Balances don't sum to zero
Make sure every expense adds the full amount to the payer and subtracts every share.
Possible improvements
- Support unequal splits by percentage or exact amounts
- Save trips to a JSON file
- Export a summary for messaging apps
Additional challenges
- 1Prove that the greedy settlement never needs more than n − 1 payments.
- 2Add currencies with conversion rates.
- 3Add an 'undo' command for the last expense.
Built and tested it yourself? Mark it to update your dashboard.