Skip to content
Python project #04Beginner

Bill Splitter

Record who paid for what and between whom, then compute exact balances and the fewest payments needed to settle up.

Estimated time
~3 hours to build
Files
4 files · 302 lines
Technologies
Python 3, dataclasses, divmod

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

Create a group of people, then record expenses as '<payer> paid <amount> for <what>', optionally followed by 'split <names>' (default everyone). Shares must add up exactly to the amount. 'balances' shows what each person is owed or owes, and 'settle' lists payments that bring every balance to zero. Unknown people, negative amounts and non-numbers are rejected.

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

TextProject tree
bill-splitter/
├── README.md
├── main.py
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

main.py

154 lines
Pythonmain.py
"""Bill Splitter: records shared expenses and works out who should pay whom.
Commands (one per line):
people Asha Ravi Meera set up the group
<payer> paid <amount> for <what> [split <names...>|split all]
balances show what everyone is owed or owes
settle the fewest payments that settle all debts
quit
Amounts are stored in paise (whole numbers) so totals never suffer rounding errors.
"""
import sys
from dataclasses import dataclass
def ask(prompt: str) -> str | None:
try:
line = input(prompt)
except EOFError:
print()
return None
if not sys.stdin.isatty():
print(line)
return line.strip()
def to_paise(text: str) -> int:
try:
rupees = float(text.replace(",", ""))
except ValueError:
raise ValueError(f"'{text}' is not an amount") from None
if rupees <= 0:
raise ValueError("amount must be positive")
return round(rupees * 100)
def rupees(paise: int) -> str:
sign = "-" if paise < 0 else ""
return f"{sign}₹{abs(paise) / 100:,.2f}"
@dataclass
class Expense:
payer: str
amount: int
description: str
shares: dict[str, int]
class Group:
def __init__(self, people: list[str]):
if len(people) < 2:
raise ValueError("a group needs at least two people")
self.people = people
self.expenses: list[Expense] = []
def find(self, name: str) -> str:
for person in self.people:
if person.lower() == name.lower():
return person
raise ValueError(f"'{name}' is not in the group ({', '.join(self.people)})")
def add(self, payer: str, amount: int, description: str, between: list[str]) -> Expense:
payer = self.find(payer)
members = self.people if not between or between == ["all"] else [self.find(n) for n in between]
base, extra = divmod(amount, len(members))
# Spread leftover paise over the first members so the shares add up exactly.
shares = {m: base + (1 if i < extra else 0) for i, m in enumerate(members)}
expense = Expense(payer, amount, description, shares)
self.expenses.append(expense)
return expense
def balances(self) -> dict[str, int]:
"""Positive: the person should receive money. Negative: they owe money."""
bal = {p: 0 for p in self.people}
for e in self.expenses:
bal[e.payer] += e.amount
for person, share in e.shares.items():
bal[person] -= share
return bal
def settlements(self) -> list[tuple[str, str, int]]:
"""Greedy: repeatedly let the biggest debtor pay the biggest creditor."""
bal = self.balances()
creditors = sorted(((v, p) for p, v in bal.items() if v > 0), reverse=True)
debtors = sorted(((-v, p) for p, v in bal.items() if v < 0), reverse=True)
payments = []
while creditors and debtors:
credit, creditor = creditors.pop(0)
debt, debtor = debtors.pop(0)
paid = min(credit, debt)
payments.append((debtor, creditor, paid))
if credit > paid:
creditors.append((credit - paid, creditor))
creditors.sort(reverse=True)
if debt > paid:
debtors.append((debt - paid, debtor))
debtors.sort(reverse=True)
return payments
def handle(group: Group | None, line: str) -> Group | None:
words = line.split()
command = words[0].lower()
if command == "people":
group = Group(words[1:])
print(f"Group created: {', '.join(group.people)}")
return group
if group is None:
raise ValueError("start with: people <name> <name> ...")
if command == "balances":
for person, value in group.balances().items():
status = "is owed" if value > 0 else "owes" if value < 0 else "is settled"
print(f" {person:<8}{status:<11}{rupees(abs(value)) if value else ''}")
return group
if command == "settle":
payments = group.settlements()
if not payments:
print(" Everyone is settled.")
for debtor, creditor, amount in payments:
print(f" {debtor} pays {creditor} {rupees(amount)}")
return group
if len(words) >= 5 and words[1].lower() == "paid" and words[3].lower() == "for":
rest = words[4:]
split_at = next((i for i, w in enumerate(rest) if w.lower() == "split"), len(rest))
description = " ".join(rest[:split_at])
between = [w.lower() for w in rest[split_at + 1:]]
expense = group.add(words[0], to_paise(words[2]), description, between)
names = ", ".join(f"{p} {rupees(s)}" for p, s in expense.shares.items())
print(f" {expense.payer} paid {rupees(expense.amount)} for {description}: {names}")
return group
raise ValueError("unknown command; try: <name> paid <amount> for <what> [split ...], balances, settle, quit")
def main() -> None:
print("Bill Splitter")
group: Group | None = None
while True:
line = ask("> ")
if line is None or line.lower() == "quit":
break
if not line:
continue
try:
group = handle(group, line)
except ValueError as error:
print(f" Error: {error}")
if group and group.expenses:
total = sum(e.amount for e in group.expenses)
print(f"{len(group.expenses)} expenses, total {rupees(total)}.")
if __name__ == "__main__":
main()

What each file does

main.py
The whole program: data classes, validation, the command loop and the report.

How to run it

Run

Terminal
python main.py # use python3 on Linux / macOS

Test against the expected output

Terminal
python main.py < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | python main.py > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
Bill Splitter
> balances
Error: start with: people <name> <name> ...
> people Asha Ravi Meera Kiran
Group created: Asha, Ravi, Meera, Kiran
> Asha paid 1200 for dinner split all
Asha paid ₹1,200.00 for dinner: Asha ₹300.00, Ravi ₹300.00, Meera ₹300.00, Kiran ₹300.00
> Ravi paid 600 for cab split Ravi Meera
Ravi paid ₹600.00 for cab: Ravi ₹300.00, Meera ₹300.00
> Meera paid 450.50 for snacks
Meera paid ₹450.50 for snacks: Asha ₹112.63, Ravi ₹112.63, Meera ₹112.62, Kiran ₹112.62
> Kiran paid 100 for tea split asha kiran
Kiran paid ₹100.00 for tea: Asha ₹50.00, Kiran ₹50.00
> Sana paid 300 for movie
Error: 'Sana' is not in the group (Asha, Ravi, Meera, Kiran)
> Asha paid -50 for nothing
Error: amount must be positive
> Ravi paid lots for gifts
Error: 'lots' is not an amount
> balances
Asha is owed ₹737.37
Ravi owes ₹112.63
Meera owes ₹262.12
Kiran owes ₹362.62
> settle
Kiran pays Asha ₹362.62
Meera pays Asha ₹262.12
Ravi pays Asha ₹112.63
> quit
4 expenses, total ₹2,350.50.
Input
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.txt and compare with tests/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

  1. 1Prove that the greedy settlement never needs more than n − 1 payments.
  2. 2Add currencies with conversion rates.
  3. 3Add an 'undo' command for the last expense.

Built and tested it yourself? Mark it to update your dashboard.