Port a Lua Inventory
Lesson 47 of 48 in Coddy's Python for Lua Developers course.
Challenge
BeginnerPort the complete Lua inventory program below. Implement inventory(lines) in inventory.py. It receives well-formed name amount strings and returns output text without a trailing newline. Names are nonempty lowercase ASCII letters; amounts are signed base-ten integers. Sum all updates for each name, including negative intermediate totals. After aggregation, discard totals of zero or less. Return positive name:total entries in ascending name order, joined by newlines, or empty if none remain. Do not read input or print in this function. The locked driver.py reads a nonnegative count and that many records, then prints the result with a final newline.
The Lua reference accumulates names in a table, obtains a deterministic order with table.sort, and uses signed decimal text helpers to avoid native numeric range and precision limits. Python replaces those helpers with int. Python dictionary iteration preserves insertion order, but this task requires explicit name sorting. Both versions aggregate before filtering. For pen 3, book 2, pen -1, return book:2 followed by 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"))Your code goes in inventory.py. The locked driver.py supplies input/output and cannot be edited.
Try it yourself
from inventory import inventory
lines = [input() for _ in range(int(input()))]
print(inventory(lines))
All lessons in Python for Lua Developers
1From Lua to Python
Run Your First Python ProgramPrinting and TextNames and Local ScopeNumbers and ConversionSuites Instead of endRecap: Rewrite a Receipt4Iteration and Transformations
Numeric for to rangepairs, ipairs, and itemsLoop Control and SkipsComprehensions and SortingRecap: Build a Ranking2Values and Decisions
nil Versus NoneTable Identity and EqualityTruthiness Is Differentelif and Value SelectionRecap: Eligibility Rules3Tables to Typed Collections
Sequence Tables to ListsTuples and Multiple ReturnsRecords to DictionariesSets and Shared TablesRecap: Clean an Inventory6Errors and Modules
Input and Exact Textpcall to Exceptionsrequire to importHints and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler