{ }codelper
updating a mapkey existsP0064

Shop inventory

Every item in the shop starts with a stock of 0.
The first line gives the number of commands m, and each of the next m lines gives one command. - "add item k": add k to that item's stock. - "sell item k": if the stock is at least k, subtract k.
Otherwise (including an item that has never been added) leave the stock unchanged and print "fail". - "show item": print the item's current stock (0 if it has never been added). After processing all commands, print on the last line the number of distinct items whose stock is 1 or more.

Input
1 ≤ m ≤ 2000, 1 ≤ k ≤ 1000.
Item names are 1 to 12 lowercase English letters
Output
one line per "fail" or show result, in command order, then a last line with the number of items still in stock
Example 1 · stdin
7
add pen 3
add cup 2
sell pen 2
sell cup 5
show pen
show ink
sell cup 2
stdout
fail
1
0
1
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 8 languages

The trap is an item seen for the first time.
Python stock[item] += k raises KeyError, C# stock[item] += k throws KeyNotFoundException, and Java int have = stock.get(item) unboxes null and throws NullPointerException.
Read with a default: Python stock.get(item, 0), Java getOrDefault or merge(item, k, Integer::sum), C# GetValueOrDefault, JS Map with get(item) ?? 0.
With a plain JS object {}, stock[item] || 0 picks up a function from Object.prototype for "constructor" and turns into a garbage string.
C++ stock[item] += k inserts 0 for a missing key, so it just works (but even a read creates the key).
The last line has its own trap: an item sold down to 0 is still in the map, so count only values of 1 or more, not len(stock).
C has no map, so it searches a name/count table from the start.
Craykon asks stock.Contains(item) on a Dict() first, and at the end walks stock.Values to count.

Pythonmain.py · 20 lines
import sys lines = sys.stdin.read().split("\n")m = int(lines[0])stock = {}for line in lines[1:m + 1]:    parts = line.split()    cmd, item = parts[0], parts[1]    have = stock.get(item, 0)    if cmd == "add":        stock[item] = have + int(parts[2])    elif cmd == "sell":        k = int(parts[2])        if have >= k:            stock[item] = have - k        else:            print("fail")    else:        print(have)print(sum(1 for v in stock.values() if v > 0))
JavaScriptmain.js · 15 lines
const lines = require("fs").readFileSync(0, "utf8").split("\n");const m = Number(lines[0]);const stock = new Map();const out = [];for (let i = 1; i <= m; i++) {  const [cmd, item, k] = lines[i].trim().split(" ");  const have = stock.get(item) ?? 0;  if (cmd === "add") stock.set(item, have + Number(k));  else if (cmd === "sell") {    if (have >= Number(k)) stock.set(item, have - Number(k));    else out.push("fail");  } else out.push(have);}out.push([...stock.values()].filter((v) => v > 0).length);console.log(out.join("\n"));
TypeScriptmain.ts · 16 lines
import { readFileSync } from "node:fs";const lines: string[] = readFileSync(0, "utf8").split("\n");const m: number = Number(lines[0]);const stock = new Map<string, number>();const out: (string | number)[] = [];for (let i = 1; i <= m; i++) {  const [cmd, item, k] = lines[i].trim().split(" ");  const have: number = stock.get(item) ?? 0;  if (cmd === "add") stock.set(item, have + Number(k));  else if (cmd === "sell") {    if (have >= Number(k)) stock.set(item, have - Number(k));    else out.push("fail");  } else out.push(have);}out.push([...stock.values()].filter((v) => v > 0).length);console.log(out.join("\n"));
JavaMain.java · 30 lines
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.HashMap;import java.util.Map; public class Main {    public static void main(String[] args) throws IOException {        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));        int m = Integer.parseInt(in.readLine().trim());        Map<String, Integer> stock = new HashMap<>();        StringBuilder out = new StringBuilder();        for (int i = 0; i < m; i++) {            String[] p = in.readLine().trim().split(" ");            int have = stock.getOrDefault(p[1], 0);            if (p[0].equals("add")) {                stock.merge(p[1], Integer.parseInt(p[2]), Integer::sum);            } else if (p[0].equals("sell")) {                int k = Integer.parseInt(p[2]);                if (have >= k) stock.put(p[1], have - k);                else out.append("fail").append('\n');            } else {                out.append(have).append('\n');            }        }        long inStock = stock.values().stream().filter(v -> v > 0).count();        out.append(inStock).append('\n');        System.out.print(out);    }}
C#Main.cs · 32 lines
using System;using System.Collections.Generic;using System.Linq; class Program{    static void Main()    {        int m = int.Parse(Console.ReadLine());        var stock = new Dictionary<string, int>();        for (int i = 0; i < m; i++)        {            string[] p = Console.ReadLine().Trim().Split(' ');            int have = stock.GetValueOrDefault(p[1]);            if (p[0] == "add")            {                stock[p[1]] = have + int.Parse(p[2]);            }            else if (p[0] == "sell")            {                int k = int.Parse(p[2]);                if (have >= k) stock[p[1]] = have - k;                else Console.WriteLine("fail");            }            else            {                Console.WriteLine(have);            }        }        Console.WriteLine(stock.Values.Count(v => v > 0));    }}
C++main.cpp · 31 lines
#include <iostream>#include <string>#include <unordered_map> int main() {    int m;    std::cin >> m;    std::unordered_map<std::string, int> stock;    for (int i = 0; i < m; i++) {        std::string cmd, item;        std::cin >> cmd >> item;        auto it = stock.find(item);        int have = it != stock.end() ? it->second : 0;        if (cmd == "add") {            int k;            std::cin >> k;            stock[item] = have + k;        } else if (cmd == "sell") {            int k;            std::cin >> k;            if (have >= k) stock[item] = have - k;            else std::cout << "fail\n";        } else {            std::cout << have << '\n';        }    }    int inStock = 0;    for (const auto& [item, count] : stock)        if (count > 0) inStock++;    std::cout << inStock << '\n';}
Cmain.c · 40 lines
#include <stdio.h>#include <string.h> /* C에는 사전이 없다: 물건 이름과 재고를 작은 표에 두고 처음부터 찾는다 */static char names[2000][13];static int counts[2000];static int size = 0; static int find_or_add(const char *item) {    for (int i = 0; i < size; i++)        if (strcmp(names[i], item) == 0) return i;    strcpy(names[size], item);    counts[size] = 0;    return size++;} int main(void) {    int m, k;    char cmd[5], item[13];    scanf("%d", &m);    for (int i = 0; i < m; i++) {        scanf("%4s %12s", cmd, item);        int at = find_or_add(item);        if (strcmp(cmd, "add") == 0) {            scanf("%d", &k);            counts[at] += k;        } else if (strcmp(cmd, "sell") == 0) {            scanf("%d", &k);            if (counts[at] >= k) counts[at] -= k;            else puts("fail");        } else {            printf("%d\n", counts[at]);        }    }    int in_stock = 0;    for (int i = 0; i < size; i++)        if (counts[i] > 0) in_stock++;    printf("%d\n", in_stock);    return 0;}
Craykonmain.cray · 41 lines
m = Console.ReadLine().ToNumber();stock = Dict();for (i = 0; i < m; i++){    p = Console.ReadLine().Trim().Split();    item = p[1];    have = 0;    if (stock.Contains(item))    {        have = stock[item];    }    if (p[0] == "add")    {        stock[item] = have + p[2].ToNumber();    }    else if (p[0] == "sell")    {        k = p[2].ToNumber();        if (have >= k)        {            stock[item] = have - k;        }        else        {            Console.WriteLine("fail");        }    }    else    {        Console.WriteLine(have);    }}inStock = 0;foreach (v in stock.Values){    if (v > 0)    {        inStock++;    }}Console.WriteLine(inStock);