PHP 재고 관리 시스템 포팅하기
Coddy의 PHP 개발자를 위한 Python 코스 레슨. 48개 중 47번째.
챌린지
초급아래 PHP 재고 관리 참조 구현을 Python으로 옮기세요. inventory.py에 inventory(lines)를 구현하고, 끝에 개행 문자를 붙이지 않은 텍스트를 반환하세요. 올바른 형식의 각 레코드에는 비어 있지 않은 소문자 ASCII 이름과 부호가 있는 10진 정수 수량이 공백으로 구분되어 들어 있습니다. 음수인 중간 합계를 포함해 모든 업데이트를 합산하세요. 합산을 모두 마친 뒤에만 합계가 0 이하인 항목을 제외하세요. 남은 이름을 오름차순으로 정렬하고 name:total 행을 개행 문자로 연결하세요. 양수인 합계가 남지 않으면 empty를 반환하세요. 잠긴 driver.py는 음수가 아닌 개수와 해당 개수만큼의 레코드를 읽은 다음, 반환된 문자열을 마지막 개행 문자와 함께 출력합니다.
PHP 참조 구현은 연관 배열, null 병합 연산자, SORT_STRING을 사용하는 ksort, 그리고 implode를 사용합니다. 십진 문자열 헬퍼 함수는 기본 PHP 정수 한계를 넘어서는 값도 보존합니다. Python의 int는 이러한 수량을 이미 지원하므로 산술 헬퍼 함수는 옮기지 마세요. Python 딕셔너리도 최종 보고서를 만들 때 명시적으로 정렬해야 합니다. 필터링하기 전에 합산하세요. 음수 업데이트 뒤에 값이 회복되는 업데이트가 올 수 있습니다.
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";코드는 inventory.py에 작성하세요. 잠긴 driver.py가 입력과 출력을 처리하며 수정할 수 없습니다.
직접 해보기
from inventory import inventory
lines = [input() for _ in range(int(input()))]
print(inventory(lines))
PHP 개발자를 위한 Python의 모든 레슨
직접 연습해 보세요: 온라인 Python 컴파일러