Editor

Run a Robot Program

Advanced · Write the code · from Grid Robot Algorithms: MOVE_FORWARD, ROTATE and CAN_MOVE

From the lesson: Grid Robot Algorithms: MOVE_FORWARD, ROTATE and CAN_MOVE

Many exam questions show a robot on a grid and ask which code segment gets it to a goal square, using four commands from the reference sheet: MOVE_FORWARD(), ROTATE_LEFT(), ROTATE_RIGHT() and CAN_MOVE(direction). The small Python robot on this page runs any path you write, so you can check a trace instead of guessing.

Read the lesson

Write run_program(grid, row, col, facing, commands). commands is a list of "F" (MOVE_FORWARD), "L" (ROTATE_LEFT) and "R" (ROTATE_RIGHT). Run them in order and return a tuple (row, col, facing) with where the robot ends.

Follow the reference sheet's rule: if an "F" would move into a "#" square or off the grid, the robot stays where it is and the program terminates. Return its position at that moment and ignore the remaining commands.

grid = ["....", ".#..", "...."]
run_program(grid, 2, 0, "right", ["F", "F", "L", "F", "F"])  ->  (0, 2, 'up')
run_program(grid, 2, 0, "up", ["F", "R", "F"])               ->  (1, 0, 'right')
DIRECTIONS = ["up", "right", "down", "left"] # clockwise order
STEPS = {"up": (-1, 0), "right": (0, 1), "down": (1, 0), "left": (0, -1)}
def run_program(grid, row, col, facing, commands):
# Return (row, col, facing) after the commands
pass

What Check runs

Your code runs first, then each of these lines, and 2 more that stay hidden. The output must match exactly.

RunsExpected output
run_program(["....", ".#..", "...."], 2, 0, "right", ["F", "F", "L", "F", "F"])(0, 2, 'up')
run_program(["....", ".#..", "...."], 2, 0, "up", ["F", "R", "F"])(1, 0, 'right')

More Grid Robot exercises

All Python exercises · 50 practice problems