Question:

A robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT with a given steps. The trace of robot movement is shown as the following:

UP 5

DOWN 3

LEFT 3

RIGHT 2

The numbers after the direction are steps. Please write a program to compute the distance from current position after a sequence of movement and original point. If the distance is a float, then just print the nearest integer.

Example:

If the following tuples are given as input to the program:

UP 5

DOWN 3

LEFT 3

RIGHT 2

Then, the output of the program should be:2

**Program:**

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import math pos = [0,0] while True: s = raw_input() if not s: break movement = s.split(" ") direction = movement[0] steps = int(movement[1]) if direction=="UP": pos[0]+=steps elif direction=="DOWN": pos[0]-=steps elif direction=="LEFT": pos[1]-=steps elif direction=="RIGHT": pos[1]+=steps else: pass print int(round(math.sqrt(pos[1]**2+pos[0]**2))) |

**Explanation:**

The **distance formula** is derived from the Pythagorean theorem. To find the **distance between two points** (x_{1},y_{1}) and (x_{2},y_{2}), all that you need to do is use the coordinates of these ordered pairs and apply the **formula** d=√{(x2−x1)2+(y2−y1)2}.This formula is used to find the distance.

**Output:**

1 2 3 4 5 6 | UP 20 RIGHT 70 UP 20 Left 60 81 |

## Leave a Reply