Inventory Commands

Inventory Commands

Hard Python Dictionaries 16 views
Explanation Complexity

Problem Statement

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.

Example

7
ADD pen 5
REMOVE pen 2
COUNT pen
REMOVE pen 10
COUNT pen
COUNT book
ADD book 1
3
0
0

Constraints

1

Input / Output Format

Input Format
First line q. Next q lines commands.
Output Format
Outputs for COUNT.
Constraints
1

Examples

Input:
7 ADD pen 5 REMOVE pen 2 COUNT pen REMOVE pen 10 COUNT pen COUNT book ADD book 1
Output:
3 0 0

Example Solution (Public)

Python
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))

Official Solution Code

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))
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.