Menu
CoddyTech

Adapte um inventário em PHP

Lição 47 de 48 do curso Python para desenvolvedores PHP da Coddy.

challenge icon

Desafio

Iniciante

Adapte a referência de inventário em PHP abaixo. Implemente inventory(lines) em inventory.py; retorne o texto sem uma quebra de linha final. Cada registro bem-formado contém um nome ASCII em minúsculas não vazio e um valor inteiro com sinal na base dez, separados por espaços em branco. Agregue todas as atualizações, incluindo totais intermediários negativos. Somente após a agregação, descarte os totais iguais ou menores que zero. Ordene os nomes restantes em ordem crescente e junte as linhas name:total com quebras de linha; retorne empty se não restar nenhum total positivo. O driver.py bloqueado lê uma contagem não negativa e essa quantidade de registros, depois imprime a string retornada com uma quebra de linha final.

A referência em PHP usa arrays associativos, coalescência de nulos, ksort com SORT_STRING e implode. Seus auxiliares para strings decimais preservam valores que excedem os limites dos inteiros nativos do PHP. O int do Python já aceita esses valores, então não adapte os auxiliares aritméticos. Um dicionário do Python ainda precisa de ordenação explícita para o relatório final. Agregue antes de filtrar: uma atualização negativa pode ser seguida por uma recuperação.

Referência em PHP: 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";

Seu código deve ficar em inventory.py. O driver.py bloqueado fornece a entrada/saída e não pode ser editado.

Experimente você mesmo

from inventory import inventory

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

Todas as lições de Python para desenvolvedores PHP

Pratique por conta própria: Compilador de Python online