Ein Lua-Inventar portieren
Lektion 47 von 48 im Kurs Python für Lua-Entwickler von Coddy.
Aufgabe
AnfängerPortiere das vollständige Lua-Inventarprogramm unten. Implementiere inventory(lines) in inventory.py. Die Funktion erhält wohlgeformte Zeichenfolgen im Format name amount und gibt Ausgabetext ohne abschließenden Zeilenumbruch zurück. Namen bestehen aus nicht leeren Kleinbuchstaben des ASCII-Zeichensatzes; Beträge sind vorzeichenbehaftete Dezimalzahlen. Addiere alle Aktualisierungen für jeden Namen, auch wenn Zwischensummen negativ sind. Verwirf nach der Aggregation Summen von null oder weniger. Gib positive Einträge im Format name:total in aufsteigender Namensreihenfolge, durch Zeilenumbrüche getrennt, zurück oder empty, falls keine Einträge übrig bleiben. Lies in dieser Funktion keine Eingaben ein und gib nichts aus. Die gesperrte Datei driver.py liest eine nichtnegative Anzahl und so viele Datensätze und gibt anschließend das Ergebnis mit einem abschließenden Zeilenumbruch aus.
Die Lua-Referenz sammelt Namen in einer Tabelle, ermittelt mit table.sort eine deterministische Reihenfolge und verwendet Hilfsfunktionen für vorzeichenbehaftete Dezimalzahlen als Text, um Einschränkungen des Wertebereichs und der Genauigkeit nativer Zahlen zu vermeiden. Python ersetzt diese Hilfsfunktionen durch int. Die Iteration über Python-Wörterbücher erhält die Einfügereihenfolge bei, aber für diese Aufgabe müssen die Namen explizit sortiert werden. Beide Versionen aggregieren vor dem Filtern. Für pen 3, book 2, pen -1 gib book:2 gefolgt von pen:2 zurück.
-- 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"))Dein Code gehört in inventory.py. Die gesperrte Datei driver.py übernimmt die Ein- und Ausgabe und kann nicht bearbeitet werden.
Probier es selbst
from inventory import inventory
lines = [input() for _ in range(int(input()))]
print(inventory(lines))
Alle Lektionen in Python für Lua-Entwickler
1Von Lua zu Python
Führe dein erstes Python-Programm ausAusgabe und TextNamen und lokaler GültigkeitsbereichZahlen und TypumwandlungBlöcke statt endRückblick: Schreibe eine Quittung um4Iteration und Transformationen
Numerische for-Schleife bis rangepairs, ipairs und itemsSchleifensteuerung und ÜberspringenComprehensions und SortierenRückblick: Ein Ranking erstellen2Werte und Entscheidungen
nil und None im VergleichIdentität und Gleichheit von TabellenTruthiness ist anderselif und WertauswahlRückblick: Zulassungsregeln3Von Tabellen zu typisierten Sammlungen
Sequenzielle Tabellen zu ListenTupel und MehrfachrückgabenDatensätze zu DictionariesMengen und gemeinsam genutzte TabellenRückblick: Ein Inventar bereinigenÜbe selbstständig: Online-Python-Compiler