Design an inventory management system
medium 80 minCount goods in several places, promise them to orders without ever promising too much, ship or let go, and explain every count.
Watch lesson4:28
Choosing places
Fewest parcels for a whole order
The point: a rule that is best for each product alone can be bad for the order. Decide whether the order is worth a search.
Gap
Two good answers, one bad order
| Cellar | Shed | Attic | |
|---|---|---|---|
| plum, want 1 | 9 | 1 | 0 |
| fig, want 1 | 9 | 0 | 1 |
FewestParcels looks at each product alone and takes the smallest sufficient place: plum from the shed, fig from the attic. Two parcels. The cellar could send both in one.Search
Try the sets of places, smallest first
Python
from itertools import combinationsdef fewest_places(wanted, stock): """stock[place][sku] is available. The smallest set of places that covers the whole order.""" places = sorted(p for p in stock if any(stock[p].get(sku, 0) > 0 for sku in wanted)) for size in range(1, len(places) + 1): for group in combinations(places, size): if all(sum(stock[p].get(sku, 0) for p in group) >= qty for sku, qty in wanted.items()): picks = [] for sku, qty in wanted.items(): for p in group: part = min(qty, stock[p].get(sku, 0)) if part: picks.append((sku, p, part)) qty -= part return picks return Nonestock = {"cellar": {"plum": 9, "fig": 9}, "shed": {"plum": 1}, "attic": {"fig": 1}}assert fewest_places({"plum": 1, "fig": 1}, stock) == [("plum", "cellar", 1), ("fig", "cellar", 1)]assert len({p for _, p, _ in fewest_places({"plum": 10, "fig": 9}, stock)}) == 2assert fewest_places({"plum": 11}, stock) is Noneprint("ok")Choosing the fewest places that cover an order contains set cover, one of the 21 problems that Karp showed to be NP-complete in 1972. For five places the search is fine. For many, use a greedy rule, and say that it is one.
Interface
The contract has to grow
Plan for the order
plan(wanted, view)sees all products- Can trade one parcel for another
- Can refuse splits by rule
- Is tested with plain dictionaries
Plan for a product
- Cannot see that the cellar is used anyway
- Its tie break is arbitrary
- Fine for one product, or when splits are free
The search is slow. Where does it run?
BreaksUnder the lock
- How
- Copy, search, hold, all inside.
- Limit
- All buyers wait for one difficult order.
- Choose when
- Small searches only.
WorksOutside, then hold or refuse
- How
- Take a snapshot, search without the lock, then try to hold the plan. If a line is short, refuse.
- Limit
- Refuses orders that another plan could fill.
- Choose when
- Little traffic for the same products.
StrongOutside, then hold, then try again
- How
- If the hold fails, take a new snapshot and search again, at most three times. Then use the greedy plan under the lock.
- Limit
- More code, and a bound on the tries.
- Choose when
- Costly plans and busy shelves. The optimistic style: hope first, check at the end.