Menu
CoddyTech

Port a PHP Inventory

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

challenge icon

Challenge

Beginner

Port 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

Practice on your own: Online Python compiler