Menu
CoddyTech

نقل كائنات الغرفة في Python

الدرس 48 من 48 في دورة Luau لمطوري Python على Coddy.

challenge icon

التحدي

متوسط

قم بنقل مرجع Python. السطر الأول من المدخلات هو سعة الغرفة (عدد غير سالب)؛ والأسطر المتبقية هي طلبات حجز كأعداد صحيحة ذات إشارة. اقبل فقط الطلبات الموجبة تمامًا والتي تتسع لها الغرفة. الطلبات الفاشلة تترك المقاعد المستخدمة دون تغيير. أرجع remaining:accepted. قم بتنفيذ Model.new(capacity) و Model:reserve(seats) في model.luau؛ حيث ترجع reserve قيمة منطقية (boolean). استخدم كائنًا جديدًا لكل تشغيل.

مرجع Python

import sys
class Room:
    def __init__(self, capacity):
        self.capacity = capacity
        self.used = 0
    def reserve(self, seats):
        if seats <= 0 or self.used + seats > self.capacity:
            return False
        self.used += seats
        return True
lines = sys.stdin.read().splitlines()
room = Room(int(lines[0]))
accepted = sum(room.reserve(int(line)) for line in lines[1:])
print(f"{room.capacity - room.used}:{accepted}")

قم بتعديل app.luau و model.luau. يقرأ الملف المقفل والمرئي main.luau الإدخال القياسي (stdin) إلى تسلسل من الأسطر، ويستدعي app.run(lines)، ثم يطبع القيمة المرجعة مع سطر جديد في النهاية. لا تطبع أي رسائل تشخيصية ولا تغير أسماء الوحدات (modules). الإدخال الفارغ يعطي تسلسلاً فارغًا. جميع المدخلات الرقمية صغيرة بما يكفي لتجنب التجاوز (overflow).

فحوصات الـ API العامة: يوفر Model.new(capacity) خاصيتي capacity و used، وتكون قيمة used في البداية صفرًا. ترجع reserve قيمة منطقية (boolean) وتحدث used فقط للطلبات الموجبة التي تتسع لها الغرفة. الغرف مستقلة عن بعضها البعض. يفحص المشغل المقفل (driver) هذا السلوك قبل استدعاء app.run. لا تطبع هذه الفحوصات أي شيء عند نجاحها.

جرّب بنفسك

-- فحوصات API العامة
do
local Model=require("./model")
local a,b=Model.new(5),Model.new(2)
assert(a:reserve(6)==false and a.used==0,"oversized reservation must not mutate")
assert(a:reserve(0)==false and a:reserve(-1)==false and a.used==0,"nonpositive requests are rejected")
assert(a:reserve(2)==true and a.used==2,"accepted seats update used")
assert(a:reserve(3)==true and a.used==5 and a.capacity==5,"exact fit succeeds without changing capacity")
assert(b.used==0 and b.capacity==2,"rooms must be independent")
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 عبر الإنترنت