Inventory Stock Report

Python for AIHard+10 XP+10

Inventory Stock Report

A shop's Inventory keeps its stock in a dictionary that maps item names to quantities.

Part 1: Inventory()

A new inventory has an empty dictionary in stock.

  • add(item, quantity) adds to that item's quantity. A new item starts from 0.
  • remove(item, quantity):
    • if the item isn't stocked, or there's less than quantity of it, change nothing and return False,
    • otherwise take the quantity away and return True. If an item's quantity drops to 0, delete it from stock.
  • count(item) returns how many of that item there are. An item that isn't stocked gives 0.
  • __repr__ returns Inventory(name=qty, name=qty) with items in alphabetical order, separated by ", ". An empty inventory is Inventory().

Part 2: stock_report(moves)

Make an inventory. moves is a list of (action, item, quantity) tuples, where action is "add" or "remove". Apply them in order. Return [str(inventory), number of failed removes].

Examples

Inventory().count('egg')
returns 0
moves = [('add', 'rice', 4), ('add', 'egg', 6), ('remove', 'rice', 9)]
returns ['Inventory(egg=6, rice=4)', 1]
moves = [("add", "pear", 2), ("add", "apple", 3), ("remove", "pear", 1)]
returns ['Inventory(apple=3, pear=1)', 0]
moves = [("remove", "milk", 1)]
returns ['Inventory()', 1]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run