Port a Java Inventory Tool
Lesson 47 of 48 in Coddy's Python for Java Developers course.
Challenge
BeginnerImplement 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
1From Java Classes to Python
Run Python Without a ClassPrinting Text and CommentsBindings, Types, and finalDivision and Numeric TypesIndentation Defines BlocksRecap: A Python Receipt4Iteration and Transformations
Enhanced Loops and rangeIndexes and Map EntriesSentinels and Loop ControlFrom Streams to ComprehensionsRecap: Stable Ranking2Values Beyond Java Primitives
None and Boolean ValuesValue Equality and IdentityTruth Tests Beyond booleanBranches and Value SelectionRecap: Missing or Eligible3Collections and Object Sharing
Lists and ArrayList HabitsTuples Without Record ClassesDictionaries and Java MapsShared References and CopiesRecap: Inventory Collections6Contracts, Errors, and Modules
Text Input and Exact OutputValueError and TypeErrorModules Versus Utility ClassesAnnotations Are Not Java TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler