A duplicate-rejection exercise checks that one receipt identifier cannot silently replace another record during a batch conversion.
Python collection exercise: reject repeated receipt IDs before committing state
Operation contract
The converter builds a private dictionary and rejects the first repeated identifier. It returns that dictionary only after all rows pass. The caller’s row list remains available for inspection and no shared ledger is mutated during a failed conversion. An invalid final row therefore cannot publish a partial result.
Failure and ownership boundary
The exercise validates positive integer identifiers and amounts, excluding bool. It checks valid rows and a repeated ID; larger programs need row-count and payload-size bounds too. Python dictionaries: insertion order and duplicate-key replacement explains what would happen without the explicit duplicate check, and Python inventory project: validate a batch before replacing stored state extends the same pattern.
Working program
def validated_ledger(rows):
if len(rows) > 1000:
raise ValueError("batch too large")
staged = {}
for identifier, amount in rows:
if type(identifier) is not int or type(amount) is not int or identifier <= 0 or amount <= 0:
raise ValueError("positive integer fields required")
if identifier in staged:
raise ValueError("repeated receipt")
staged[identifier] = amount
return staged
print(validated_ledger([(41, 125), (42, 75)]))
try:
validated_ledger([(41, 125), (41, 75)])
except ValueError:
print("repeated receipt rejected")Output
{41: 125, 42: 75}
repeated receipt rejectedCosts and limits
Expected dictionary work is O(n) with O(n) staged storage for bounded ordinary integer keys. Returning a complete batch is intentional; a streaming sink needs a separate rollback/publication design.
Common Mistakes
- Do not publish a partially validated batch.
- A dictionary overwrite is not duplicate rejection.
Connected lessons
Python dictionaries: insertion order and duplicate-key replacement, Python input exercise: accept an explicit integer grammar, Python inventory project: validate a batch before replacing stored state.
Follow the ownership and update boundary
Python assignment exercise: verify pair feasibility separately from optimality.
