使用 Python 语言编写的停车场模拟程序

本程序模拟一个只有一个大门可供汽车进出的狭长停车场,停车场内只有一个可停放 N 辆汽车的通道(N 为 5)。汽车按到达时间顺序由南向北排列。如果停车场已满,则后来的汽车只能在门外的便道(候车场)等待。一旦有车开走,候车场上的第一辆车便可开入停车场。如果停车场内某辆汽车要开走,则在它之后进入的车辆必须先退出停车场在待停区等候,等该车开出大门外,待停区的车辆再按原次序进入停车场。

以下是用 Python 语言编写的停车场模拟程序:pythonclass Car: def init(self, plate): self.plate = plate

class ParkingLot: def init(self, capacity): self.capacity = capacity self.cars = [] self.waiting_cars = []

def enter(self, car):        if len(self.cars) < self.capacity:            self.cars.append(car)            print('Car with plate ' + car.plate + ' has entered the parking lot.')        else:            if len(self.waiting_cars) < self.capacity:                self.waiting_cars.append(car)                print('Car with plate ' + car.plate + ' is waiting outside the parking lot.')            else:                print('Car with plate ' + car.plate + ' cannot enter the parking lot or the waiting area is full.')

def exit(self, car):        if car in self.cars:            self.cars.remove(car)            print('Car with plate ' + car.plate + ' has exited the parking lot.')            if len(self.waiting_cars) > 0:                waiting_car = self.waiting_cars.pop(0)                self.cars.append(waiting_car)                print('Car with plate ' + waiting_car.plate + ' has entered the parking lot from the waiting area.')        elif car in self.waiting_cars:            self.waiting_cars.remove(car)            print('Car with plate ' + car.plate + ' has left the waiting area.')        else:            print('Car with plate ' + car.plate + ' is not in the parking lot or the waiting area.')

def print_status(self):        print('Parking lot status:')        print('Cars in parking lot:', [car.plate for car in self.cars])        print('Cars in waiting area:', [car.plate for car in self.waiting_cars])

parking_lot = ParkingLot(5)

while True: print('Enter command (enter, exit, status, quit):') command = input() if command == 'enter': print('Enter car plate number:') plate = input() car = Car(plate) parking_lot.enter(car) elif command == 'exit': print('Enter car plate number:') plate = input() car = Car(plate) parking_lot.exit(car) elif command == 'status': parking_lot.print_status() elif command == 'quit': break else: print('Invalid command.')

程序包含以下主要功能:

  • Car 类: 表示一辆汽车,包含车牌号信息。- ParkingLot 类: 表示停车场,包含以下属性和方法: - capacity: 停车场容量。 - cars: 存储停车场内车辆的列表,使用列表实现栈的功能。 - waiting_cars: 存储候车场车辆的列表,使用列表实现队列的功能。 - enter(car): 车辆进入停车场。 - exit(car): 车辆离开停车场。 - print_status(): 打印停车场状态。

程序使用循环不断地接受用户输入的命令,执行相应的操作。用户可输入以下命令:

  • enter: 输入车牌号,将车辆加入停车场或候车场。- exit: 输入车牌号,将车辆从停车场或候车场移除。- status: 打印停车场状态。- quit: 退出程序。
Python 停车场管理模拟程序:使用栈和队列实现

原文地址: https://www.cveoy.top/t/topic/m1kr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录