Workbench / Household Numbers: the Mathematics Capstone
S2 · B1·02
Reading the Statement
Stage 2, after chapter 2: amounts written in lakh-and-crore grouping, international grouping and European format, read into whole paise by one strict reader, printed back in Indian grouping, and a statement reconciled so that a mistyped amount can't slip through.
Stage 2: reading the statement
The brief
What you'll build. A reader for bank-statement amounts in the formats you'll actually meet (₹1,23,456.50, ₹123,456.50, and statements exported with European settings, 123.456,50), a printer that shows paise back as rupees in Indian grouping, and a reconciliation: opening balance plus every transaction must equal the closing balance, to the paisa.
Why a real household needs this. Statements come from different banks, apps and export settings. A reader that guesses separators can turn ₹45,678.90 into ₹45.68 (exercises, senior exercise S2), and a single mistyped amount in a hand-kept ledger throws every later figure off. Reconciliation is how accountants have caught both for centuries.
Why now. Chapter 2 explains that grouping and separators are conventions, not part of the number, and that a numeral is only readable under a known convention.
What you'll have at the end. statement.py with to_paise, indian and reconcile; your stage 1 ledger reconciled against a real statement (or the sample); a note of any discrepancy and its cause.
Theory to own
- Same number, three spellings. Write ₹12,34,567.80 in international grouping and in European format. What is unchanged? (Chapter: "Reading large numbers: grouping is a convention".)
- Why refuse instead of guess? "1.234" is one thousand two hundred and thirty-four, or one and a bit. What should a reader do when it isn't told which? (Chapter: the warning "Separators are not digits"; exercises, C1.)
- Lakh grouping as a rule. State the Indian grouping rule precisely (how many digits in each group, from the right). Is "1,2,34,567" valid? (Chapter: lakh and crore.)
- Why reconciliation catches typos. If one amount is mistyped, why must the reconciliation fail? Can two errors cancel? (Chapter 1: combining; chapter 3 will add checks like casting out nines.)
Build it
Step 1: by hand. Take five amounts from a statement and write each in all three spellings. Then add your stage 1 ledger's payments to last month's closing balance and compare with this month's statement.
Step 2: the reader. One function, told the format, that refuses anything not exactly in it, and a printer for Indian grouping:
"""Household numbers, stage 2: read a bank statement whatever its number format, then reconcile it."""
FORMATS = {
# name: (thousands separator, decimal separator, Indian grouping allowed)
"in": (",", ".", True), # ₹1,23,456.50 or ₹123,456.50
"eu": (".", ",", False), # 123.456,50
}
def to_paise(text, fmt):
"""Read an amount in a known format into whole paise. Refuse anything that doesn't match it exactly."""
sep, dec, lakh_ok = FORMATS[fmt]
t = text.strip().replace("₹", "").strip()
sign = -1 if t.startswith("-") else 1
t = t.lstrip("-")
whole, _, frac = t.partition(dec)
groups = whole.split(sep)
by_thousands = all(len(g) == 3 for g in groups[1:]) and 1 <= len(groups[0]) <= 3
by_lakh = lakh_ok and len(groups[-1]) == 3 and all(len(g) == 2 for g in groups[1:-1]) and 1 <= len(groups[0]) <= 2
if not all(g.isdigit() for g in groups) or not (len(groups) == 1 or by_thousands or by_lakh):
raise ValueError(f"{text!r} doesn't look like a {fmt} amount")
if frac and not (frac.isdigit() and len(frac) <= 2):
raise ValueError(f"{text!r}: at most two digits after the decimal separator")
return sign * (int("".join(groups)) * 100 + int((frac + "00")[:2]))
def indian(p):
"""Whole paise as rupees with Indian grouping: ₹1,23,456.50"""
s, r = str(abs(p) // 100), f"{abs(p) % 100:02d}"
head, tail = s[:-3], s[-3:]
pairs = [head[max(0, i - 2):i] for i in range(len(head), 0, -2)][::-1]
return ("-" if p < 0 else "") + "₹" + "".join(x + "," for x in pairs) + tail + "." + r
def reconcile(st):
opening, closing = to_paise(st["opening"], st["format"]), to_paise(st["closing"], st["format"])
moves = [to_paise(x, st["format"]) for x in st["lines"]]
gap = closing - (opening + sum(moves))
print(f"opening {indian(opening)} movements {indian(sum(moves))} closing {indian(closing)} ->",
"reconciles" if gap == 0 else f"does NOT reconcile: off by {indian(gap)}")
good = {"format": "eu", "opening": "123.456,50", "closing": "97.716,25",
"lines": ["-22.000,00", "-1.840,50", "-1.254,00", "15.000,00", "-15.000,00", "-645,75"]}
reconcile(good)
reconcile(dict(good, lines=good["lines"][:-1] + ["-6.457,5"])) # one amount mistyped
for bad in ["1.23.456,50", "123,456.50", "12.34"]:
try:
to_paise(bad, "eu")
except ValueError as e:
print("refused:", e)
print(indian(to_paise("1,23,456.50", "in")), indian(to_paise("12,345,678.90", "in")), indian(to_paise("-500", "in")))
opening ₹1,23,456.50 movements -₹25,740.25 closing ₹97,716.25 -> reconciles
opening ₹1,23,456.50 movements -₹31,552.00 closing ₹97,716.25 -> does NOT reconcile: off by ₹5,811.75
refused: '1.23.456,50' doesn't look like a eu amount
refused: '123,456.50': at most two digits after the decimal separator
refused: '12.34' doesn't look like a eu amount
₹1,23,456.50 ₹1,23,45,678.90 -₹500.00
Step 3: read the output. The first statement reconciles. In the second, ₹645.75 was keyed as 6.457,5 (₹6,457.50), and the reconciliation fails by exactly the difference, ₹5,811.75. The reader refuses Indian grouping in a European-format statement, a comma where a European statement has its decimal comma, and a value with the wrong number of digits between separators. International input is printed back in Indian grouping, because the number is the same and only the reader of the output changed.
Step 4: your own statement. Run it on last month's real statement (exported in whatever format your bank uses) and your stage 1 ledger. If it doesn't reconcile, find the lines responsible: a missing transaction, a duplicate, a wrong sign, or a typo, as above.
Senior and architect lens
- Configured, not detected. The format is a property of the source (this bank's export), set once, never guessed per value. Detection by inspecting values is exactly how "1.234" goes wrong.
- Reconciliation is an independent check. Field-by-field validation can't see a wrong but well-formed amount; a balance identity can. Payment systems reconcile ledgers against bank files every day for this reason.
- One internal representation. Every format converts to whole paise at the edge and back at the edge; nothing in between handles text. That's chapter 2's number-versus-numeral distinction as an architecture.
Evidence
statement.pyand its output on the sample and on your own statement.- A reconciliation that passes, or a note explaining the gap and what you corrected.
- Your hand conversions from step 1.
Carry forward
Stage 3, after chapter 3, adds the month's totals by category, checks them three ways (by hand with carries, by estimate, by casting out nines), and finds what a ₹0.10 floating-point error does to a year of totals.