Port a PHP Inventory
Lesson 47 of 48 in Coddy's Python for PHP Developers course.
Challenge
BeginnerPort the PHP inventory reference below. Implement inventory(lines) in inventory.py; return text without a trailing newline. Each well-formed record contains a nonempty lowercase ASCII name and a signed base-ten integer amount, separated by whitespace. Aggregate every update, including negative intermediate totals. Only after aggregation, discard totals of zero or less. Sort remaining names in ascending order and join name:total lines with newlines; return empty if no positive totals remain. The locked driver.py reads a nonnegative count and that many records, then prints your returned string with a final newline.
The PHP reference uses associative arrays, null coalescing, ksort with SORT_STRING, and implode. Its decimal-string helpers preserve values beyond native PHP integer limits. Python int already supports these amounts, so do not port the arithmetic helpers. A Python dictionary still needs explicit sorting for the final report. Aggregate before filtering: a negative update can be followed by a recovery.
PHP reference: inventory.php
<?php
// Decimal strings preserve integer totals beyond PHP's native integer range.
function normalizeAmount(string $text): string {
$negative = $text[0] === '-';
$digits = ltrim(ltrim($text, '+-'), '0');
return $digits === '' ? '0' : ($negative ? '-' : '') . $digits;
}
function compareMagnitude(string $a, string $b): int {
return strlen($a) <=> strlen($b) ?: strcmp($a, $b);
}
function addMagnitude(string $a, string $b): string {
$i = strlen($a) - 1; $j = strlen($b) - 1; $carry = 0; $out = '';
while ($i >= 0 || $j >= 0 || $carry) {
$sum = $carry + ($i >= 0 ? (int)$a[$i--] : 0) + ($j >= 0 ? (int)$b[$j--] : 0);
$out = (string)($sum % 10) . $out;
$carry = intdiv($sum, 10);
}
return $out;
}
// Requires a >= b in magnitude.
function subtractMagnitude(string $a, string $b): string {
$i = strlen($a) - 1; $j = strlen($b) - 1; $borrow = 0; $out = '';
while ($i >= 0) {
$digit = (int)$a[$i--] - $borrow - ($j >= 0 ? (int)$b[$j--] : 0);
$borrow = $digit < 0 ? 1 : 0;
$out = (string)($digit + 10 * $borrow) . $out;
}
return ltrim($out, '0') ?: '0';
}
function addAmount(string $left, string $right): string {
$left = normalizeAmount($left); $right = normalizeAmount($right);
$ln = $left[0] === '-'; $rn = $right[0] === '-';
$a = ltrim($left, '-'); $b = ltrim($right, '-');
if ($ln === $rn) {
return normalizeAmount(($ln ? '-' : '') . addMagnitude($a, $b));
}
$order = compareMagnitude($a, $b);
if ($order === 0) return '0';
if ($order > 0) return normalizeAmount(($ln ? '-' : '') . subtractMagnitude($a, $b));
return normalizeAmount(($rn ? '-' : '') . subtractMagnitude($b, $a));
}
function inventory(array $lines): string {
$stock = [];
foreach ($lines as $line) {
[$name, $amount] = preg_split('/\s+/', trim($line));
$stock[$name] = addAmount($stock[$name] ?? '0', $amount);
}
ksort($stock, SORT_STRING);
$output = [];
foreach ($stock as $name => $amount) {
if ($amount !== '0' && $amount[0] !== '-') $output[] = $name . ':' . $amount;
}
return $output ? implode("\n", $output) : 'empty';
}
$count = (int)trim(fgets(STDIN));
$lines = [];
for ($i = 0; $i < $count; $i++) $lines[] = rtrim(fgets(STDIN), "\r\n");
echo inventory($lines), "\n";Your code goes in inventory.py. The locked driver.py supplies input/output and cannot be edited.
Try it yourself
from inventory import inventory
lines = [input() for _ in range(int(input()))]
print(inventory(lines))
All lessons in Python for PHP Developers
1From PHP to Python
Run Your First Python ProgramEcho, Strings, and printVariables Without Dollar SignsDivision and Numeric TextIndentation and SuitesRecap: Rewrite a Receipt4Iteration and Transformations
Foreach and rangeKeys, Items, and enumerateWhile Without IncrementFilters and Sort KeysRecap: Build a Ranking2Values and Decisions
Null, None, and Missing KeysStrict Equality Is Not isThe Zero String TrapElif and Value SelectionRecap: Eligibility Rules3Arrays and Python Collections
PHP Arrays and Python ListsDestructuring and TuplesKeys, Null, and getArray Copies and List AliasesRecap: Clean an Inventory6Input, Errors, and Modules
CLI Input and Exact OutputConversion Errors and CleanupImports Instead of requireType Hints Are Not PHP TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler