Menu
CoddyTech

최종: 예약 시스템

Coddy의 C# 개발자를 위한 Python 코스 레슨. 48개 중 48번째.

challenge icon

챌린지

초급

서로 협력하는 두 개의 객체와 프로그램 진입점을 작성하세요. Room(capacity)는 수용 인원(capacity)과 이름을 좌석 수로 매핑하는 새로운 bookings 딕셔너리를 관리합니다. 이 클래스의 reserve(name, seats) 및 cancel(name) 메서드는 거부 시 ValueError를 발생시킵니다. BookingDesk(room)은 전달된 room을 저장합니다. handle(command)는 ok 또는 invalid를 반환하고, 형식에 맞게 작성된 명령을 현재 room에 위임하며, ValueError를 포착하고 절대로 출력하지 않습니다. 입력은 음수가 아닌 수용 인원, 음수가 아닌 명령 개수, 그리고 해당 개수만큼의 줄로 구성됩니다. 명령은 reserve name seats 또는 cancel name 형식입니다. 이름은 비어 있지 않은 소문자 ASCII 토큰입니다. 예약에는 int로 변환 가능한 양의 좌석 수, 새로운 이름, 그리고 충분한 공간이 필요합니다. 취소에는 기존 이름이 필요합니다. 잘못된 형식의 정수, 알 수 없는 작업, 잘못된 필드 개수, 빈 명령, 또는 실패한 비즈니스 규칙은 상태를 변경하지 않고 거부합니다. main()은 명령당 하나의 상태를 출력한 다음, 이름순으로 정렬된 available:N 및 활성 name:seats 줄을 출력합니다. 취소된 이름은 다시 예약할 수 있습니다. 수용 인원이 0이면 예약을 받지 않습니다. 드라이버 검사는 독립된 room, 거부 후 변경되지 않은 상태, 그리고 대체 room으로의 위임을 확인합니다. 모든 데이터는 메모리에 저장됩니다.

C# 전환 체크포인트

C# 인터페이스는 room 계약을 선언할 수 있습니다. Python에서는 전달된 객체에 위임함으로써 드라이버가 호환 가능한 room으로 대체할 수 있으므로 상속 검사가 필요하지 않습니다.

C# 참고 발췌문: 실행 가능한 문은 using System;을 가정한 것이며, 타입 전용 발췌문은 선언된 계약을 설명합니다.

interface IRoom { void Reserve(string name, int seats); void Cancel(string name); }

Python 패턴

class Desk:
    def __init__(self, room):
        self.room = room
    def cancel(self, name):
        return self.room.cancel(name)

편집 가능한 구현 파일: room.py, booking_desk.py, main.py. 잠긴 driver.py는 제공되는 실행기 또는 입력/출력 하네스이며 변경할 수 없습니다.

프롬프트 없이 제공된 입력 계약을 사용하세요. 각 줄의 끝에 줄바꿈을 포함하여 필요한 줄만 출력하세요.

직접 해보기

from room import Room
from booking_desk import BookingDesk
from main import main

main()

probe_room = Room(4)
other_room = Room(4)
probe_room.reserve("a", 3)
assert probe_room.capacity == 4 and probe_room.bookings == {"a": 3}
assert other_room.bookings == {}
for name, seats in [("a", 1), ("b", 2), ("c", 0), ("d", -1)]:
    try:
        probe_room.reserve(name, seats)
    except ValueError:
        pass
    else:
        raise AssertionError("Invalid reservation accepted")
assert probe_room.bookings == {"a": 3}
try:
    probe_room.cancel("missing")
except ValueError:
    pass
else:
    raise AssertionError("Unknown cancellation accepted")
probe_room.cancel("a")
assert probe_room.bookings == {}
probe_desk = BookingDesk(other_room)
assert probe_desk.room is other_room
assert probe_desk.handle("reserve x 4") == "ok"
assert other_room.bookings == {"x": 4}
class ProbeRoom:
    def __init__(self):
        self.calls = []
    def reserve(self, name, seats):
        self.calls.append(("reserve", name, seats))
        if seats == 9:
            raise ValueError("probe rejection")
    def cancel(self, name):
        self.calls.append(("cancel", name))
probe = ProbeRoom()
probe_desk.room = probe
assert probe_desk.handle("reserve y 2") == "ok"
assert probe_desk.handle("cancel y") == "ok"
assert probe_desk.handle("reserve z 9") == "invalid"
assert probe_desk.handle("reserve a bad") == "invalid"
assert probe.calls == [("reserve", "y", 2), ("cancel", "y"), ("reserve", "z", 9)]

C# 개발자를 위한 Python의 모든 레슨

직접 연습해 보세요: 온라인 Python 컴파일러