"""Internal demonstration: exact, deterministic ledger reconciliation.""" import re def reconcile(entries): seen, balances = {}, {} for entry in entries: if not isinstance(entry, dict): raise ValueError('Each entry must be an object') key, account, amount = (entry.get(k) for k in ('id', 'account', 'amount')) if not all(isinstance(v, str) and v.strip() for v in (key, account, amount)): raise ValueError('id, account and amount must be non-empty strings') if not re.fullmatch(r'-?(?:0|[1-9]\d*)\.\d{2}', amount): raise ValueError('amount must be a decimal string with two places') cents = int(amount.replace('.', '')) value = (account, cents) if key in seen: if seen[key] != value: raise ValueError('Conflicting duplicate id: ' + key) continue seen[key] = value balances[account] = balances.get(account, 0) + cents def money(cents): return ('-' if cents < 0 else '') + str(abs(cents) // 100) + '.' + str(abs(cents) % 100).zfill(2) return {'accounts': [{'account': a, 'net': money(balances[a])} for a in sorted(balances)], 'total': money(sum(balances.values())), 'unique_entries': len(seen)}