移植 Lua 库存系统
Coddy 面向 Lua 开发者的 Python 课程的第 47 课,共 48 课。
挑战
入门移植下面完整的 Lua 库存程序。在 inventory.py 中实现 inventory(lines)。它接收格式正确的 name amount 字符串,并返回不带末尾换行符的输出文本。名称由非空的小写 ASCII 字母组成;数量是带符号的十进制整数。将每个名称的所有更新值相加,包括中间的负数总计。汇总后,舍弃小于或等于零的总计。返回按名称升序排列、以换行符连接的正数 name:total 条目;如果没有剩余条目,则返回 empty。不要在此函数中读取输入或打印内容。锁定的 driver.py 会读取一个非负数量和相应数量的记录,然后打印结果,并在末尾添加换行符。
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 在线编译器