Port a JavaScript Inventory
Lesson 47 of 48 in Coddy's Python for JavaScript Developers course.
Challenge
BeginnerPort 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
1From JavaScript to Python
Run Your First Python ProgramPrint, Comments, and StringsVariables Without let or constNumbers and ConversionBlocks Use IndentationRecap: Rewrite a Receipt4Iteration and Transformations
for Loops Iterate ValuesIndexes and Dict Iterationwhile, break, and continueComprehensions and SortingRecap: Build a Ranking2Values and Decisions
None, True, and FalseEquality and IdentityTruthiness and Short-CircuitBranches and ExpressionsRecap: Eligibility Rules3Collections and References
Lists Instead of ArraysTuples and UnpackingDictionaries and RecordsSets, Aliasing, and CopiesRecap: Clean an Inventory6Reliable Python Programs
Input and Output ContractsExceptions and ValidationModules and the Main GuardReading Type HintsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler