python模拟电梯运行
时间: 2023-09-28 22:03:51 浏览: 77
好的,这是一个比较常见的面试题了。下面是一个简单的 Python 代码示例,可以模拟电梯的运行。
```
class Elevator:
def __init__(self):
self.current_floor = 1
self.destinations = []
self.direction = 1 # 1: up, -1: down
def add_destination(self, floor):
if floor not in self.destinations:
self.destinations.append(floor)
self.destinations.sort()
if floor > self.current_floor:
self.direction = 1
else:
self.direction = -1
def move(self):
if not self.destinations:
return
self.current_floor += self.direction
if self.current_floor == self.destinations[0]:
print(f"Arrived at floor {self.current_floor}")
self.destinations.pop(0)
if not self.destinations:
self.direction = 0
elif self.destinations[0] > self.current_floor:
self.direction = 1
else:
self.direction = -1
else:
print(f"Moving to floor {self.current_floor}")
# Example usage:
elevator = Elevator()
elevator.add_destination(5)
elevator.add_destination(2)
elevator.add_destination(8)
while elevator.direction != 0:
elevator.move()
```
上面的代码定义了一个 Elevator 类,包含了电梯当前所在的楼层、待停的楼层、运行方向等信息,以及添加目的地和移动电梯的方法。在示例中,我们添加了三个目的地楼层,然后通过一个 while 循环不断移动电梯,直到所有目的地都到达并停止运行。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)