Menu
CoddyTech

Port a JavaScript Inventory

Lesson 47 of 48 in Coddy's Python for JavaScript Developers course.

challenge icon

Challenge

Beginner

Port the behavior of the complete JavaScript reference below to a complete Python program. The reference uses an example array; your program must read standard input instead. Input starts with a nonnegative record count, then exactly that many name amount lines. Names are nonempty lowercase ASCII letters; amounts are signed integers. Sum every update for each name, including negative intermediate totals. After all updates, discard totals of zero or less. Print remaining name:total lines in ascending name order, or exactly empty if no positive totals remain. Duplicate names accumulate; do not overwrite, clamp each update, or filter before aggregation. All input is well formed. The example reference prints book:2 then pen:2.

JavaScript reference

function inventory(lines) {
  const stock = new Map();
  for (const line of lines) {
    const [name, amount] = line.split(" ");
    stock.set(name, (stock.get(name) ?? 0) + Number(amount));
  }
  const names = [...stock.keys()].filter(name => stock.get(name) > 0).sort();
  return names.length ? names.map(name => `${name}:${stock.get(name)}`).join("\n") : "empty";
}
console.log(inventory(["pen 3", "book 2", "pen -1"]));

Implement inventory(lines) in editable inventory.py: it receives the record strings and returns the complete output string, with newline separators but no trailing newline. The supplied imports require no extra setup. The locked driver.py reads standard input and prints the returned string with a final newline.

Try it yourself

from inventory import inventory

lines = [input() for _ in range(int(input()))]
print(inventory(lines))

All lessons in Python for JavaScript Developers

Practice on your own: Online Python compiler