Lua 인벤토리 포팅하기
Coddy의 Lua 개발자를 위한 Python 코스 레슨. 48개 중 47번째.
챌린지
초급아래의 완전한 Lua 재고 프로그램을 포팅하세요. inventory.py에서 inventory(lines)를 구현하세요. 이 함수는 형식이 올바른 name amount 문자열을 받아 마지막에 개행 문자가 없는 출력 텍스트를 반환합니다. 이름은 비어 있지 않은 소문자 ASCII 문자이며, 수량은 부호가 있는 십진 정수입니다. 중간 합계가 음수인 경우도 포함하여 이름별로 모든 업데이트를 합산하세요. 합산한 뒤 합계가 0 이하인 항목은 제외하세요. 양수인 name:total 항목을 이름 오름차순으로 정렬해 개행 문자로 연결하여 반환하고, 남은 항목이 없으면 empty를 반환하세요. 이 함수에서는 입력을 읽거나 출력하지 마세요. 잠긴 driver.py는 0 이상의 개수와 그만큼의 레코드를 읽은 다음, 결과를 마지막 개행 문자와 함께 출력합니다.
Lua 참조 구현은 테이블에 이름을 누적하고, table.sort를 사용해 일관된 순서를 구하며, 네이티브 숫자의 범위와 정밀도 제한을 피하기 위해 부호가 있는 십진 텍스트 헬퍼를 사용합니다. Python에서는 이러한 헬퍼 대신 int를 사용합니다. Python 딕셔너리의 반복은 삽입 순서를 보존하지만, 이 작업에서는 이름을 명시적으로 정렬해야 합니다. 두 버전 모두 합산한 후 필터링합니다. pen 3, book 2, pen -1이 주어지면 book:2 다음에 pen:2를 반환하세요.
-- Decimal text arithmetic avoids Lua integer overflow and float rounding.
local function parse(text)
local negative = text:sub(1, 1) == "-"
local digits = text:gsub("^[+-]", ""):gsub("^0+", "")
if digits == "" then return false, "0" end
return negative, digits
end
local function compare(a, b)
if #a ~= #b then return #a < #b and -1 or 1 end
if a == b then return 0 end
return a < b and -1 or 1
end
local function add_magnitude(a, b)
local i, j, carry, reversed = #a, #b, 0, {}
while i > 0 or j > 0 or carry > 0 do
local x = i > 0 and tonumber(a:sub(i, i)) or 0
local y = j > 0 and tonumber(b:sub(j, j)) or 0
local total = x + y + carry
reversed[#reversed + 1] = string.char(48 + total % 10)
carry = math.floor(total / 10)
i, j = i - 1, j - 1
end
return table.concat(reversed):reverse()
end
-- Precondition: a >= b in magnitude.
local function subtract_magnitude(a, b)
local j, borrow, reversed = #b, 0, {}
for i = #a, 1, -1 do
local x = tonumber(a:sub(i, i))
local y = j > 0 and tonumber(b:sub(j, j)) or 0
local difference = x - y - borrow
borrow = difference < 0 and 1 or 0
if difference < 0 then difference = difference + 10 end
reversed[#reversed + 1] = string.char(48 + difference)
j = j - 1
end
local result = table.concat(reversed):reverse():gsub("^0+", "")
return result == "" and "0" or result
end
local function add(left, right)
local ln, a = parse(left)
local rn, b = parse(right)
local negative, result
if ln == rn then
negative, result = ln, add_magnitude(a, b)
elseif compare(a, b) >= 0 then
negative, result = ln, subtract_magnitude(a, b)
else
negative, result = rn, subtract_magnitude(b, a)
end
return negative and result ~= "0" and "-" .. result or result
end
local count = assert(tonumber(io.read("*l")))
local stock = {}
for _ = 1, count do
local name, amount = io.read("*l"):match("^(%l+)%s+([+-]?%d+)$")
stock[name] = add(stock[name] or "0", amount)
end
local names = {}
for name, total in pairs(stock) do
if total ~= "0" and total:sub(1, 1) ~= "-" then names[#names + 1] = name end
end
table.sort(names)
local output = {}
for _, name in ipairs(names) do output[#output + 1] = name .. ":" .. stock[name] end
print(#output == 0 and "empty" or table.concat(output, "\n"))코드는 inventory.py에 작성하세요. 잠긴 driver.py가 입력과 출력을 처리하며 수정할 수 없습니다.
직접 해보기
from inventory import inventory
lines = [input() for _ in range(int(input()))]
print(inventory(lines))
Lua 개발자를 위한 Python의 모든 레슨
직접 연습해 보세요: 온라인 Python 컴파일러