Menu
CoddyTech

Porta un inventario PHP

Lezione 47 di 48 del corso Python per sviluppatori PHP di Coddy.

challenge icon

Sfida

Principiante

Converti il riferimento PHP per l'inventario riportato di seguito. Implementa inventory(lines) in inventory.py; restituisci il testo senza una nuova riga finale. Ogni record ben formato contiene un nome non vuoto in ASCII minuscolo e un importo intero con segno in base dieci, separati da spazi bianchi. Aggrega ogni aggiornamento, inclusi i totali intermedi negativi. Solo dopo l'aggregazione, scarta i totali pari o inferiori a zero. Ordina i nomi rimanenti in ordine crescente e unisci le righe name:total con nuove righe; restituisci empty se non rimane alcun totale positivo. Il driver.py bloccato legge un conteggio non negativo e altrettanti record, quindi stampa la stringa restituita con una nuova riga finale.

Il riferimento PHP usa array associativi, il coalescing nullo, ksort con SORT_STRING e implode. I suoi helper per le stringhe decimali preservano valori che superano i limiti degli interi nativi di PHP. Python int supporta già questi importi, quindi non convertire gli helper aritmetici. Un dizionario Python richiede comunque un ordinamento esplicito per il rapporto finale. Aggrega prima di filtrare: a un aggiornamento negativo può seguirne uno che ripristina il totale.

Riferimento 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";

Il tuo codice va inserito in inventory.py. Il driver.py bloccato gestisce input/output e non può essere modificato.

Provalo tu

from inventory import inventory

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

Tutte le lezioni di Python per sviluppatori PHP

Esercitati da solo: Compilatore Python online