Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Chương trình thiết kế hệ thống đỗ xe trong Python

Giả sử ta muốn thiết kế hệ thống đỗ xe. Bãi đỗ có 3 loại chỗ: lớn (big), trung (medium), nhỏ (mỗi loại có số chỗ cố định). Tạo lớp OurParkingSystem với 2 phương thức:

  • constructor(big, medium, small): khởi tạo số chỗ cho từng loại
  • addCar(carType): kiểm tra và đỗ xe loại carType

Ba loại: 1=big, 2=medium, 3=small. Xe chỉ đỗ đúng loại. Nếu hết chỗ trả về False, ngược lại đỗ xe và trả về True.

Ví dụ: OurParkingSystem(2, 0, 1)

  • addCar(3) → True (đỗ xe nhỏ)
  • addCar(2) → False (hết chỗ trung)
  • addCar(3) → False (hết chỗ nhỏ)
  • addCar(1) → True (đỗ xe lớn)
  • addCar(1) → True (đỗ xe lớn)
  • addCar(1) → False (hết chỗ lớn)

Giải thuật

  1. constructor: self.sp = [0, big, medium, small]
  2. addCar(carType):
    • Nếu self.sp[carType] > 0: self.sp[carType]--, trả về True
    • Trả về False

Ví dụ (Python)

class OurParkingSystem:
    def __init__(self, big, medium, small):
        self.sp = [0, big, medium, small]
    
    def addCar(self, carType):
        if self.sp[carType] > 0:
            self.sp[carType] -= 1
            return True
        return False

ps = OurParkingSystem(2, 0, 1)
print(ps.addCar(3))  # True
print(ps.addCar(2))  # False
print(ps.addCar(3))  # False
print(ps.addCar(1))  # True
print(ps.addCar(1))  # True
print(ps.addCar(1))  # False

Input

ps.addCar(3) ps.addCar(2) ps.addCar(3) ps.addCar(1) ps.addCar(1) ps.addCar(1)

Output

True False False True True False