"""Original Lawfare Academy reference lab. Fictional work orders; Python 3 standard library. Run: python python_estimator.py. Read the assertions before changing the policy. """ import csv import io from dataclasses import dataclass @dataclass(frozen=True) class WorkOrder: order_id: str customer: str minutes: int rate_cents_hour: int def cents(self): # Half-up rounding, one line at a time; nonnegative integers only. return (self.minutes * self.rate_cents_hour + 30) // 60 def parse_batch(text): reader = csv.DictReader(io.StringIO(text)) expected = ['id', 'customer', 'minutes', 'rate_cents_hour'] if reader.fieldnames != expected: raise ValueError('Wrong columns or order') accepted, rejected, seen = [], [], set() for line, row in enumerate(reader, 2): try: if None in row or any(v is None for v in row.values()): raise ValueError('Column count mismatch') oid, customer = row['id'].strip(), row['customer'].strip() if not oid or not customer or oid in seen: raise ValueError('Missing identity or duplicate order id') minutes, rate = int(row['minutes']), int(row['rate_cents_hour']) if minutes < 0 or rate < 0: raise ValueError('Negative quantity') accepted.append(WorkOrder(oid, customer, minutes, rate)) seen.add(oid) except (ValueError, TypeError) as error: rejected.append({'line': line, 'reason': str(error)}) return accepted, rejected def allocate(cents, count): if type(cents) is not int or type(count) is not int or cents < 0 or count <= 0: raise ValueError('Nonnegative integer cents and positive integer count required') share, remainder = divmod(cents, count) return [share + (i < remainder) for i in range(count)] def report(orders): result = {} for order in orders: record = result.setdefault(order.customer, {'orders': 0, 'cents': 0}) record['orders'] += 1 record['cents'] += order.cents() return result def main(): fixture = 'id,customer,minutes,rate_cents_hour\nA,Ada,35,6250\nB,Ada,60,6250\nC,Ben,0,5000\nD,Ben,-1,5000\nA,Ada,60,6250\n' orders, errors = parse_batch(fixture) assert len(orders) == 3 and len(errors) == 2 assert report(orders) == {'Ada': {'orders': 2, 'cents': 9896}, 'Ben': {'orders': 1, 'cents': 0}} assert len(orders) + len(errors) == 5 assert allocate(1000, 3) == [334, 333, 333] for amount in range(30): for count in range(1, 12): shares = allocate(amount, count) assert sum(shares) == amount and max(shares) - min(shares) <= 1 assert WorkOrder('X', 'X', 1, 30).cents() == 1 assert report([]) == {} print('PASS: reconciliation, duplicates, zero, invalid input, half-up rounding and allocation invariants') print(report(orders), errors) if __name__ == '__main__': main()