Luau 인벤토리 이식하기
Coddy의 Luau 개발자를 위한 Python 코스 레슨. 48개 중 47번째.
챌린지
초급아래의 Luau 재고 프로그램 전체를 포팅하세요. inventory.py에 inventory(lines)를 구현하세요. 이 함수는 형식이 올바른 name amount 문자열을 받아 마지막에 줄바꿈이 없는 출력 텍스트를 반환합니다. 이름은 비어 있지 않은 소문자 ASCII 문자로 이루어져 있으며, 수량은 부호가 있는 10진 정수입니다. 중간 합계가 음수인 경우를 포함해 각 이름의 모든 갱신 값을 합산하세요. 합산한 뒤 합계가 0 이하인 항목은 제외하세요. 양수인 name:total 항목을 이름의 오름차순으로 정렬하고 줄바꿈으로 연결해 반환하세요. 남는 항목이 없으면 empty를 반환하세요. 이 함수에서는 입력을 읽거나 출력하지 마세요. 잠긴 driver.py는 음이 아닌 개수와 해당 개수만큼의 레코드를 읽은 다음, 마지막에 줄바꿈을 붙여 결과를 출력합니다.
Luau 참조 코드는 이름을 테이블에 누적하고, table.sort를 사용해 결정적인 순서를 얻으며, 기본 숫자 자료형의 범위와 정밀도 제한을 피하기 위해 부호가 있는 10진수 텍스트 헬퍼 함수를 사용합니다. Python에서는 이러한 헬퍼 함수 대신 int를 사용합니다. Python 딕셔너리의 반복 순서는 삽입 순서를 유지하지만, 이 과제에서는 이름을 명시적으로 정렬해야 합니다. 두 버전 모두 필터링 전에 값을 합산합니다. pen 3, book 2, pen -1의 경우 book:2 다음에 pen:2를 반환하세요.
-- Decimal text arithmetic avoids Luau floating-point precision loss.
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))
Luau 개발자를 위한 Python의 모든 레슨
직접 연습해 보세요: 온라인 Python 컴파일러