程序员心头常想的电梯算法,我用Python实现了一种极简单的

大神打扰一下,程序员心头常想的电梯算法,我用Python实现了一种极简单的
最新回答
卿弦季鸢

2026-10-21 17:10:37

这段代码实现了一个简单的电梯模拟算法,其核心逻辑是先上行到最高目标楼层,再下行到最低目标楼层,属于典型的“货梯式”运行模式。以下是对代码的详细分析及优化建议:

代码逻辑分析
  1. 全局变量

    targetFloorList:存储所有目标楼层(未排序)。

    sortFloors:排序后的目标楼层列表(升序)。

    location:电梯当前楼层(由用户输入)。

  2. 关键函数

    setTargetFloor():将新目标楼层合并到列表并排序。

    moveLocation(sign):模拟电梯移动(sign=1上行,sign=-1下行),每次移动耗时1秒。

    completeFloor():检查当前楼层是否为目标楼层,若是则移除并打印剩余楼层。

  3. 主循环

    通过比较location和sortFloors[-1](当前最高目标楼层)决定移动方向。

    每次移动后调用completeFloor(),直到所有目标楼层被处理。

现存问题
  1. 效率低下

    电梯必须无条件上行到最高楼层,即使下方有更紧急的请求(如用户输入location=1但目标楼层为[8, -3],电梯会先升到8层再下降)。

    未考虑同方向顺路楼层的优化(如上行途中可捎带更高楼层的目标)。

  2. 代码缺陷

    全局变量过多(sortFloors, minFloor, maxFloor未使用),易引发维护问题。

    输入location为字符串时可能报错(未做类型校验)。

    终止条件if sortFloors == []冗余(while循环已检查)。

  3. 功能局限

    无法动态添加新目标楼层(如运行中有人按按钮)。

    未处理电梯最大/最小楼层限制(如地下3层是否合法)。

优化建议1. 改进算法逻辑
  • SCAN算法(电梯扫描算法):电梯沿一个方向移动,依次处理所有同向请求,直到最高/最低层后反向。优化代码示例:def elevator_scan(): target_floors = sorted(targetFloorList) current = location direction = 1 # 1:上行, -1:下行 while target_floors: if direction == 1: next_floors = [f for f in target_floors if f >= current] else: next_floors = [f for f in target_floors if f <= current] if not next_floors: direction *= -1 continue next_floor = next_floors[0] if direction == 1 else next_floors[-1] step = 1 if direction == 1 else -1 while current != next_floor: current += step print("location:", current) if current in target_floors: print(f"Arrived at floor {current}") target_floors.remove(current) direction *= -1
2. 增强代码健壮性
  • 添加输入校验:try: location = int(input("location: "))except ValueError: print("Invalid input! Using default location 0.") location = 0
  • 限制楼层范围(如MIN_FLOOR=-3, MAX_FLOOR=10)。
3. 支持动态请求
  • 使用队列实时处理新目标楼层:from collections import dequetarget_queue = deque()def add_target(floor): target_queue.append(floor)
完整优化代码import timefrom collections import dequeclass Elevator: def __init__(self, initial_location=0): self.location = initial_location self.targets = [] self.direction = 1 # 1:上行, -1:下行 def add_target(self, floor): if floor not in self.targets: self.targets.append(floor) self.targets.sort() def move(self): if not self.targets: print("No targets left.") return # 确定下一个目标楼层 if self.direction == 1: next_floors = [f for f in self.targets if f >= self.location] else: next_floors = [f for f in self.targets if f <= self.location] if not next_floors: self.direction *= -1 return self.move() next_floor = next_floors[0] if self.direction == 1 else next_floors[-1] step = 1 if self.direction == 1 else -1 while self.location != next_floor: self.location += step print("location:", self.location) time.sleep(1) if self.location in self.targets: print(f"Arrived at floor {self.location}") self.targets.remove(self.location) self.direction *= -1# 示例使用elevator = Elevator(location=1)elevator.add_target(5)elevator.add_target(-3)elevator.add_target(8)while elevator.targets: elevator.move()print("All floors completed!")总结
  • 原代码问题:逻辑简单但效率低,缺乏动态处理能力。
  • 优化方向:采用SCAN算法、支持实时请求、增强输入校验。
  • 扩展建议:可进一步实现最短寻道优先(SSTF)或LOOK算法以提升效率。

通过优化,电梯模拟将更贴近实际场景,同时代码结构也更清晰易维护。