Reconcile two inventory counts with Counter subtraction
Reconcile two inventory counts with Counter subtraction
Author: Batu. AI assistance was used to draft this article.
A stock reconciliation often needs two reports: items counted physically but not fully represented in the ledger, and ledger quantities not found on the shelf. collections.Counter makes both reports direct. Construct one Counter from each SKU-to-quantity mapping, then calculate physical - ledger for overages and ledger - physical for shortages. The example prints widget and label as overages, while cable and adapter are shortages.
Counter’s - operator is deliberately positive-only: zero results and negative results are absent from its output. That is useful here because each report should contain only actionable quantities. It also means a matching SKU such as cable will not appear in the overage report, and a missing key behaves like a count of zero. The assertions check the two expected Counter results before presentation.
Do not use this form when the sign itself is required in one combined audit record. Instead, copy one counter and call its mutating subtract() method; unlike -, it preserves zero and negative counts. Counts should represent comparable inventory units: reconciling cartons against individual pieces will produce arithmetically valid but operationally misleading results. SKU keys must also be hashable.
Source: Python Counter documentation.
from collections import Counter
ledger = Counter({"widget": 8, "cable": 5, "adapter": 2})
physical = Counter({"widget": 10, "cable": 3, "label": 4})
overages = physical - ledger
shortages = ledger - physical
assert overages == Counter({"widget": 2, "label": 4})
assert shortages == Counter({"cable": 2, "adapter": 2})
print("overages:", dict(overages))
print("shortages:", dict(shortages))
Expected stdout
overages: {'widget': 2, 'label': 4}
shortages: {'cable': 2, 'adapter': 2}
Comments
Post a Comment