A shop keeps track of how many pieces of each item it has: the item's stock. The stock can never go below 0, and it changes only when pieces are sold or new ones arrive. So the stock is a private field, changed only through two methods that check the rules. The item's name has no rules to protect, so it stays a field any code can read.
Implement the class InventoryItem:
InventoryItem(name, stock)creates an item with that name and that many pieces in stock. The name is kept in a fieldnamethat other code can read.sell(n)sellsnpieces. Ifnis at least 1 and at most the stock, it lowers the stock bynand returnstrue. Otherwise it changes nothing and returnsfalse: selling 0 pieces, a negative number of pieces, or more pieces than there are in stock is refused.restock(n)addsnpieces to the stock whennis at least 1, and ignoresnotherwise. It returns nothing.getStock()returns the stock. It is the only way for other code to read it.
Keep the stock private the way the Access Modifiers lesson does in your language: self._stock in Python (private by convention), a #stock field in JavaScript, and the private keyword in Java, C++, C#, TypeScript, Kotlin, Scala and Swift. In Kotlin and Scala the constructor's second parameter is named initialStock, and the private stock starts at its value.
Each test case creates one item, then applies a list of operations to it, in order. The output has one line per test case: the item's name and a colon, then what each sell and getStock call returns, separated by spaces, with sell's answer printed as True or False. The starter code spells these names the way your language does: get_stock in Python, Sell, Restock and GetStock in C#.
Example 1:
Input:
InventoryItem("Pencil", 5)
sell(3)
getStock()
sell(5)
getStock()
restock(10)
getStock()
Output: Pencil: True 2 False 2 12
Explanation: Selling 3 of the 5 pencils works and leaves 2. Selling 5 more is refused, because only 2 are left,
and the stock stays 2. restock(10) brings it to 12.
Example 2:
Input:
InventoryItem("Mug", 4)
sell(4)
getStock()
sell(1)
getStock()
Output: Mug: True 0 False 0
Explanation: Selling all 4 mugs is allowed and leaves 0. With nothing left, even one mug can't be sold.
Example 3:
Input:
InventoryItem("Lamp", 2)
sell(0)
sell(-3)
restock(0)
restock(-5)
getStock()
restock(1)
sell(3)
getStock()
Output: Lamp: False False 2 True 0
Explanation: Selling 0 or -3 lamps is refused, and restocking 0 or -5 lamps is ignored, so the stock is still 2.
After restock(1) there are 3 lamps, and selling all 3 works.
Constraints:
- A name is one word of English letters.
0 <= stock <= 104when the item is created. -104 <= n <= 104in everysellandrestock.- A test case has from 1 to 1000 operations, and at least one of them is a
sellor agetStock.
Free plan: 30 tutor messages. PRO is unlimited.
