44. Where does the robot end up?
A robot starts at the point (0, 0) on a grid and follows a string of moves, one letter per step:
Umoves it up: y goes up by 1;Dmoves it down: y goes down by 1;Rmoves it right: x goes up by 1;Lmoves it left: x goes down by 1.
Write a function final_position(moves) that takes the string of moves and returns where the robot ends up, as a
tuple (x, y). With no moves it stays at (0, 0).
The tests show a tuple in square brackets, [x, y], as JSON writes it, and a list [x, y] counts as a right answer
too.
Example 1
moves = "UURRD"[2, 1]Example 2
moves = "LDLD"[-2, -2]Example 3
moves = ""[0, 0]Constraints
moveshas 0 to 100 characters, eachU,D,LorR.
Submit also runs 7 more tests you can't see.
Practises Tuples (lesson 10).
- Keep two numbers,
x = 0andy = 0, and change one of them for each letter:UandDchangey,RandLchangex. - A dictionary can hold each move's step as a tuple,
{"U": (0, 1), "R": (1, 0), ...}, anddx, dy = steps[move]unpacks it into two names. return x, yreturns a tuple: the comma makes it, brackets or not.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def final_position(moves):
"""Find where the robot stops.
moves: str, made of U, D, L and R; may be empty
Returns: tuple of two ints, (x, y), starting from
(0, 0)
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.