Menu
CoddyTech

הסבת מלאי Python

שיעור 47 מתוך 48 בקורס Luau למפתחי Python של Coddy.

challenge icon

אתגר

בינוני

הסב את תוכנית הייחוס ב-Python למודולים ב-Luau. כל שורת קלט מורכבת משם באותיות ASCII קטנות, נקודתיים ודלתא של מספר שלם בעל סימן. קבץ לפי שם, שמור רק סכומים סופיים חיוביים, מיין שמות בסדר עולה והחזר רשומות name=total מופרדות בפסיקים. החזר empty כאשר לא נותר דבר. ממש את inventory.aggregate(lines) ב-inventory.luau; app מעצב את התוצאה. כל שורות הקלט תקינות.

תוכנית ייחוס ב-Python

import sys
counts = {}
for line in sys.stdin.read().splitlines():
    name, quantity = line.split(":")
    counts[name] = counts.get(name, 0) + int(quantity)
rows = [f"{name}={counts[name]}" for name in sorted(counts) if counts[name] > 0]
print(",".join(rows) if rows else "empty")

ערוך את app.luau, inventory.luau. הקובץ הנעול והגלוי main.luau קורא את stdin לרצף של שורות, קורא ל-app.run(lines), ומדפיס את הערך המוחזר שלו עם שורה חדשה אחת בסוף. אין להדפיס הודעות אבחון או לשנות את שמות המודולים. קלט ריק מניב רצף ריק. כל הקלטים המספריים קטנים מספיק כדי למנוע גלישה.

בדיקות API ציבורי: inventory.aggregate(lines) מחזירה טבלה חדשה של דלתאות בעלות סימן שמסוכמות, תוך שמירה על סכומים השווים לאפס. קלט ריק מחזיר טבלה ריקה. העיצוב והסינון מתבצעים ב-app. הדרייבר הנעול בודק התנהגות זו לפני הקריאה ל-app.run. בדיקות אלה אינן מדפיסות דבר כאשר הן מצליחות.

נסו בעצמכם

-- בדיקות API ציבורי
do
local inventory=require("./inventory")
local counts=inventory.aggregate({"pen:3","pen:-1","book:0"})
assert(counts.pen==2 and counts.book==0,"aggregate must sum signed deltas by name")
local empty=inventory.aggregate({})
assert(next(empty)==nil,"aggregate empty input returns an empty table")
assert(counts.pen==2,"aggregation calls retain independent result state")
end
local app = require("./app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))

כל השיעורים ביחידה Luau למפתחי Python

תרגלו בעצמכם: קומפיילר Luau אונליין