Inventory Manager
Completed
Manage a shop inventory with commands: add ITEM QTY PRICE, sell ITEM QTY (print not enough ITEM if short), report (print each item sorted as ITEM QTY @ PRICE with 2-decimal price, then value: TOTAL).
Input
Line 1: n. Then n commands.
Output
The messages and reports.
Example
Input
6 add pen 10 1.5 add book 2 12 sell pen 4 sell book 3 add pen 5 1.75 report
Output
not enough book book 2 @ 12.00 pen 11 @ 1.75 value: 43.25
Editor
Python
Hints
Store items in a dict of small objects.
Handle each command in its own branch.
Solution explanation
Real programs are mostly this: a data structure plus a loop that applies commands to it.
Show solution
from dataclasses import dataclass
@dataclass
class Stock:
qty: int
price: float
inventory = {}
for _ in range(int(input())):
cmd, *args = input().split()
if cmd == "add":
name, qty, price = args[0], int(args[1]), float(args[2])
if name in inventory:
inventory[name].qty += qty
inventory[name].price = price
else:
inventory[name] = Stock(qty, price)
elif cmd == "sell":
name, qty = args[0], int(args[1])
stock = inventory.get(name)
if stock is None or stock.qty < qty:
print(f"not enough {name}")
else:
stock.qty -= qty
elif cmd == "report":
for name in sorted(inventory):
s = inventory[name]
print(f"{name} {s.qty} @ {s.price:.2f}")
print(f"value: {sum(s.qty * s.price for s in inventory.values()):.2f}")