Menu
CoddyTech

Pythonの部屋オブジェクトを移植する

Coddyの「Python開発者のためのLua」コースのレッスン 48/48。

challenge icon

チャレンジ

中級

Pythonの参照実装を移植してください。最初の入力行は0以上の部屋の定員で、残りの行は符号付き整数の予約リクエストです。厳密に正のリクエストのうち、定員内に収まるものだけを受け付けてください。失敗したリクエストでは、使用済みの座席数は変わりません。remaining:acceptedを返してください。model.luaにModel.new(capacity)とModel:reserve(seats)を実装してください。reserveは真偽値を返します。実行ごとに新しいオブジェクトを使用してください。

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.luaとmodel.luaを編集してください。表示されているロック済みのmain.luaは、stdinを行のシーケンスとして読み込み、app.run(lines)を呼び出し、返された値を最後に改行を1つ付けて出力します。診断メッセージを出力したり、モジュール名を変更したりしないでください。入力が空の場合は空のシーケンスになります。すべての数値入力は、オーバーフローを避けられる範囲内です。

公開APIの確認: Model.new(capacity)はcapacityとusedを公開し、usedの初期値は0です。reserveは真偽値を返し、正のリクエストが定員内に収まる場合にのみusedを更新します。各部屋は独立しています。ロックされたドライバーは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))

Python開発者のためのLuaのすべてのレッスン

自分で練習してみよう: Luaオンラインコンパイラ