Menu
CoddyTech

Port a Java Inventory Tool

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

challenge icon

Challenge

Beginner

Implement inventory(lines) in inventory.py; do not read standard input or print in this function. It receives well-formed name amount record strings, with nonempty lowercase ASCII names and signed integer amounts. Sum all changes by name, retaining negative intermediate totals. Only after aggregation discard totals <= 0. Return positive entries as name:total in ascending name order, joined by newlines without a trailing newline; return empty if none remain. The locked driver reads a nonnegative count and that many records, calls your function, and prints its result with a final newline. Match the Java reference below using Python dict/int rather than TreeMap/BigInteger. Its sample prints book:2 then pen:2.

Editable files: inventory.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.

Java reference (complete Main.java)

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class Main {
    static String inventory(List<String> lines) {
        Map<String, BigInteger> stock = new TreeMap<>();
        for (String line : lines) {
            String[] parts = line.split(" ");
            stock.merge(parts[0], new BigInteger(parts[1]), BigInteger::add);
        }
        List<String> result = new ArrayList<>();
        for (var entry : stock.entrySet()) {
            if (entry.getValue().signum() > 0) {
                result.add(entry.getKey() + ":" + entry.getValue());
            }
        }
        return result.isEmpty() ? "empty" : String.join("\n", result);
    }
    public static void main(String[] args) {
        System.out.println(inventory(List.of("pen 3", "book 2", "pen -1")));
    }
}

Try it yourself

from inventory import inventory

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

All lessons in Python for Java Developers

Practice on your own: Online Python compiler