Inventory Commands
Python
Hard
3 views
Problem Description
You have an inventory counts dictionary. Commands: ADD item x, REMOVE item x, COUNT item. Missing item starts at 0. REMOVE cannot make count below 0 (stop at 0). For COUNT output current count.
Input Format
First line q. Next q lines commands.
Output Format
Outputs for COUNT.
Sample Test Case
Input:
7
ADD pen 5
REMOVE pen 2
COUNT pen
REMOVE pen 10
COUNT pen
COUNT book
ADD book 1
Official Solution
import sys
lines=sys.stdin.read().splitlines()
if not lines: sys.exit(0)
q=int(lines[0].strip())
mp={}
out=[]
for i in range(1,1+q):
parts=(lines[i] if i<len(lines) else '').split()
if not parts: continue
cmd=parts[0]
item=parts[1]
if cmd=='COUNT':
out.append(str(mp.get(item,0)))
else:
x=int(parts[2])
if cmd=='ADD':
mp[item]=mp.get(item,0)+x
else:
cur=mp.get(item,0)-x
if cur<=0:
if item in mp:
del mp[item]
else:
mp[item]=cur
sys.stdout.write('\
'.join(out))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!