Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรม Python ออกแบบระบบจอดรถ (Parking System Design)

ออกแบบ Class ParkingSystem จำลองระบบจอดรถ 3 ขนาด: Big (1), Medium (2), Small (3) มี Slot จำกัดแต่ละขนาด

Requirements

  • Constructor(big, medium, small): เริ่มต้นจำนวน Slot แต่ละขนาด
  • addCar(carType): พยายามจอดรถ ประเภท 1=Big, 2=Medium, 3=Small คืน True หากจอดได้, False หากเต็ม

ตัวอย่าง

ParkingSystem(2, 0, 1)  # 2 Big, 0 Medium, 1 Small
addCar(3) → True  (Small: 1→0)
addCar(2) → False (Medium: 0 slots)
addCar(3) → False (Small: 0 slots)
addCar(1) → True  (Big: 2→1)
addCar(1) → True  (Big: 1→0)
addCar(1) → False (Big: 0 slots)

โค้ด Python (Class-based)

class ParkingSystem:
    """
    ระบบจอดรถ 3 ขนาด: Big(1), Medium(2), Small(3)
    """
    
    def __init__(self, big: int, medium: int, small: int):
        # ใช้ List Index 1,2,3 สำหรับ Car Type (Index 0 ไม่ใช้)
        self.slots = [0, big, medium, small]
    
    def addCar(self, carType: int) -> bool:
        """
        พยายามจอดรถ
        
        Args:
            carType: 1=Big, 2=Medium, 3=Small
        
        Returns:
            bool - True หากจอดสำเร็จ, False หาก Slot เต็ม
        """
        if self.slots[carType] > 0:
            self.slots[carType] -= 1
            return True
        return False


# ทดสอบ
if __name__ == "__main__":
    # Example from problem
    ps = ParkingSystem(2, 0, 1)
    
    test_cases = [3, 2, 3, 1, 1, 1]
    expected = [True, False, False, True, True, False]
    
    print("Parking System Test:")
    print(f"Initial Slots: Big=2, Medium=0, Small=1")
    print("-" * 40)
    
    for i, (car_type, exp) in enumerate(zip(test_cases, expected)):
        result = ps.addCar(car_type)
        car_name = {1: "Big", 2: "Medium", 3: "Small"}[car_type]
        status = "✓" if result == exp else "✗"
        print(f"{status} addCar({car_type}) [{car_name:6s}] => {result} (expected {exp})")
        print(f"    Remaining: Big={ps.slots[1]}, Medium={ps.slots[2]}, Small={ps.slots[3]}")


# Alternative: Dictionary-based (More Readable)
class ParkingSystemDict:
    def __init__(self, big: int, medium: int, small: int):
        self.slots = {
            1: big,    # Big
            2: medium, # Medium
            3: small   # Small
        }
    
    def addCar(self, carType: int) -> bool:
        if self.slots.get(carType, 0) > 0:
            self.slots[carType] -= 1
            return True
        return False


# ทดสอบ Dictionary Version
print("\nDictionary Version:")
ps2 = ParkingSystemDict(2, 0, 1)
for car_type in [3, 2, 3, 1, 1, 1]:
    result = ps2.addCar(car_type)
    print(f"addCar({car_type}) => {result}, Slots: {ps2.slots}")

ผลลัพธ์

Parking System Test:
Initial Slots: Big=2, Medium=0, Small=1
----------------------------------------
✓ addCar(3) [Small ] => True (expected True)
    Remaining: Big=2, Medium=0, Small=0
✓ addCar(2) [Medium] => False (expected False)
    Remaining: Big=2, Medium=0, Small=0
✓ addCar(3) [Small ] => False (expected False)
    Remaining: Big=2, Medium=0, Small=0
✓ addCar(1) [Big   ] => True (expected True)
    Remaining: Big=1, Medium=0, Small=0
✓ addCar(1) [Big   ] => True (expected True)
    Remaining: Big=0, Medium=0, Small=0
✓ addCar(1) [Big   ] => False (expected False)
    Remaining: Big=0, Medium=0, Small=0

Complexity Analysis

  • Time: O(1) ต่อ Operation
  • Space: O(1) - Fixed 3 Slots

การขยายฟีเจอร์ (Extensions)

class AdvancedParkingSystem:
    def __init__(self, big, medium, small):
        self.slots = {1: big, 2: medium, 3: small}
        self.parked_cars = {1: [], 2: [], 3: []}  # Track License Plates
        self.car_types = {1: "Big", 2: "Medium", 3: "Small"}
    
    def addCar(self, carType, license_plate=None):
        if self.slots.get(carType, 0) > 0:
            self.slots[carType] -= 1
            if license_plate:
                self.parked_cars[carType].append(license_plate)
            return True
        return False
    
    def removeCar(self, carType, license_plate=None):
        """นำรถออก (เพิ่ม Slot)"""
        if license_plate and license_plate in self.parked_cars[carType]:
            self.parked_cars[carType].remove(license_plate)
            self.slots[carType] += 1
            return True
        elif not license_plate and self.parked_cars[carType]:
            self.parked_cars[carType].pop()
            self.slots[carType] += 1
            return True
        return False
    
    def get_status(self):
        return {
            self.car_types[k]: {"available": v, "occupied": len(self.parked_cars[k])}
            for k, v in self.slots.items()
        }

LeetCode Reference

Problem 1603: "Design Parking System" - Easy