Complete the code to assign an elevator to a request based on the nearest elevator.
def assign_elevator(request_floor, elevators): nearest = None min_distance = float('inf') for elevator in elevators: distance = abs(elevator.current_floor - [1]) if distance < min_distance: min_distance = distance nearest = elevator return nearest
The request_floor is used to calculate the distance from each elevator's current floor to the requested floor.
Complete the code to update the elevator's direction after assigning a new target floor.
def update_direction(elevator, target_floor): if target_floor > elevator.current_floor: elevator.direction = [1] elif target_floor < elevator.current_floor: elevator.direction = 'down' else: elevator.direction = 'idle'
If the target floor is above the current floor, the elevator should move 'up'.
Fix the error in the code that checks if an elevator can pick up a request on its way.
def can_pickup(elevator, request_floor): if elevator.direction == 'up' and elevator.current_floor <= [1] <= elevator.target_floor: return True elif elevator.direction == 'down' and elevator.target_floor <= [1] <= elevator.current_floor: return True return False
The request_floor should be checked if it lies between the current floor and target floor in the elevator's direction.
Fill both blanks to correctly update the elevator's target floors queue and direction after servicing a floor.
def service_floor(elevator, floor): if floor in elevator.target_floors: elevator.target_floors.remove([1]) if not elevator.target_floors: elevator.direction = [2]
Remove the serviced floor from target_floors and set direction to 'idle' if no targets remain.
Fill all three blanks to implement a function that selects the best elevator for a request considering direction and distance.
def select_best_elevator(request_floor, elevators): best_elevator = None best_score = float('inf') for elevator in elevators: if elevator.direction == [1] and can_pickup(elevator, request_floor): score = abs(elevator.current_floor - [2]) else: score = abs(elevator.current_floor - [3]) + 10 if score < best_score: best_score = score best_elevator = elevator return best_elevator
The elevator moving 'up' and able to pick up the request is preferred. The score uses request_floor if pickup is possible, else target_floor plus penalty.
