设停车场内只有一个可停放N假设N为5辆汽车的狭长通道且只有一个大门可供汽车进出。汽车在停车场内按车辆到达时间的先后顺序依次由南向北排列。若车场内已停满N辆车则后来的汽车只能在门外的便道也就是候车场等候一旦有车开走则排在候车场上的第一辆车便可开入停车场假定候车场同样只有N辆汽车的容量。当停车场内某辆汽车要开走时在它之后进入的车辆必须先退出停车场在待停区等候等该车开出大门外待停区的车辆再按原次序进入停
以下是Python实现:
class ParkingLot:
def __init__(self, capacity):
self.capacity = capacity
self.cars = [] # 停车场内的车辆(栈)
self.waiting_cars = [] # 候车场内的车辆(队列)
def park(self, car):
if len(self.cars) < self.capacity:
self.cars.append(car)
print(f"车牌号为{car}的车辆成功进入停车场")
else:
if len(self.waiting_cars) < self.capacity:
self.waiting_cars.append(car)
print(f"车牌号为{car}的车辆进入候车场")
else:
print(f"候车场已满,车牌号为{car}的车辆无法进入")
def leave(self, car):
if car in self.cars:
self.cars.remove(car)
print(f"车牌号为{car}的车辆成功离开停车场")
if len(self.waiting_cars) > 0:
waiting_car = self.waiting_cars.pop(0)
self.cars.append(waiting_car)
print(f"候车场内的车辆{waiting_car}成功进入停车场")
elif car in self.waiting_cars:
self.waiting_cars.remove(car)
print(f"车牌号为{car}的车辆成功离开候车场")
else:
print(f"停车场和候车场内均无车牌号为{car}的车辆")
def status(self):
print(f"停车场内的车辆为:{self.cars}")
print(f"候车场内的车辆为:{self.waiting_cars}")
测试代码:
parking_lot = ParkingLot(5)
parking_lot.park("粤A12345")
parking_lot.park("粤A67890")
parking_lot.park("粤B11111")
parking_lot.park("粤B22222")
parking_lot.park("粤C33333")
parking_lot.park("粤D44444")
parking_lot.status()
parking_lot.leave("粤A12345")
parking_lot.leave("粤B11111")
parking_lot.park("粤E55555")
parking_lot.status()
输出结果:
车牌号为粤A12345的车辆成功进入停车场
车牌号为粤A67890的车辆成功进入停车场
车牌号为粤B11111的车辆成功进入停车场
车牌号为粤B22222的车辆成功进入停车场
车牌号为粤C33333的车辆成功进入停车场
候车场已满,车牌号为粤D44444的车辆无法进入
停车场内的车辆为:['粤A12345', '粤A67890', '粤B11111', '粤B22222', '粤C33333']
候车场内的车辆为:['粤D44444']
车牌号为粤A12345的车辆成功离开停车场
车牌号为粤B11111的车辆成功离开停车场
候车场内的车辆粤E55555成功进入停车场
停车场内的车辆为:['粤A67890', '粤B22222', '粤C33333', '粤D44444', '粤E55555']
候车场内的车辆为:[]
原文地址: http://www.cveoy.top/t/topic/bs6y 著作权归作者所有。请勿转载和采集!