python 模拟停车状态
时间: 2023-10-12 21:18:24 浏览: 59
这是一个简单的停车状态模拟程序:
```python
class ParkingLot:
def __init__(self, capacity):
self.capacity = capacity
self.available = capacity
self.cars = set()
def park(self, car):
if self.available > 0:
self.cars.add(car)
self.available -= 1
print(f"{car} parked. Available spaces: {self.available}/{self.capacity}")
else:
print(f"No available space for {car}")
def unpark(self, car):
if car in self.cars:
self.cars.remove(car)
self.available += 1
print(f"{car} unparked. Available spaces: {self.available}/{self.capacity}")
else:
print(f"{car} not found in parking lot")
# create a parking lot with 5 spaces
parking_lot = ParkingLot(5)
# park some cars
parking_lot.park("car1")
parking_lot.park("car2")
parking_lot.park("car3")
parking_lot.park("car4")
parking_lot.park("car5")
parking_lot.park("car6")
# unpark some cars
parking_lot.unpark("car3")
parking_lot.unpark("car6")
parking_lot.unpark("car7")
```
输出:
```
car1 parked. Available spaces: 4/5
car2 parked. Available spaces: 3/5
car3 parked. Available spaces: 2/5
car4 parked. Available spaces: 1/5
car5 parked. Available spaces: 0/5
No available space for car6
car3 unparked. Available spaces: 1/5
car6 not found in parking lot
car7 not found in parking lot
```