Notepad/enter/Coding Tips (Classical)/Project Vault/Past Projects/Amazon Programming Tips/Coding Assessment/Practice Problems/Amazon Robot Python problem...

2.9 KiB

Robot problem (most frequently asked)

Remember: think of each problem when you are coding them like a story. You have to explain to yourself where you are in the story and if it helps to write it down then please do that as well. You will have to create and author the story as you go of course. Retell it in the way that it makes most sense for you.

Revisiting the Robot Problem

Think about the way you would first tackle this problem and use the 6 tips to quickly devise the answer.

Find a way to retell this problem as quickly as you can - a robot is at the origin of a coordinate map (0,0 Y axis N+1 X Axis W -1 R(0,0) E +2 S -1

Instructions: G: go straight 1 L: turn anti-clockwise 90 degrees R: turn clockwise 90 degrees

Robot performs the instructions in order and keeps looping those same instructions. Return true iff there is a circle s.t. iff the robot can never leave the circle (return true if the robot is iterating the same way in circle instruction set and doesnt not stop following circle instructions) ^ that would be the base case.

circle equation: x^2 + y^2 = r^2

given a point (h, k) that the robot is now in update the circle equation. circle equation gets updated: (x-h)^2 +(y-k)^2 = r^2

how to check if there is a circle: if coordinates x, y, h, k, r are any of the coordinates.

an example input may be: "GGLGG" true --> check for circle example: GG false --> not for cicle

GL --> true W --> true

for the (0,0) case x^2 + y^2 = r^2 if x

c = [i,k]

input = [] for r in input[i,k] if "G": c[1] = +2 if L: c[0] = -1 if R: c[0] = +1 if r = 0 return true else continue.


Solution: You were on the right track but have to practice with syntax more. a directions array needs to be intiialized with:

directions = [(0,1),(1,0)(0,-1)(-1,0)]

each time G, L, or R called the direction and then x,y coordiante as well as d is also updated but first make sure to set them to 0.

x = 0
y = 0 
d = 0 

your for loop was pretty much spot on but here is the appropriate syntax for that in python.

for instruction in instructions: 
	if instruction == 'G':
	x += direction[d][0]
	y += directions[d][1]
//the base case is north, G 

	if instruction == 'L':
	d = (d+3) % 4 

	else:
		d = (d+1) %4 
		
//this makes sense. you will only be calling a reference to any of the directions if you are actually going forward one of the four coordinates aka the G.  otherwise you are simily just updating d. 

return (x,y) == (0,0) or d > 0
	

This will mean that ultimately the coordinate will return to (x,y) or that the direction will continue being greater than the syntax for it to return a boolean is by giving it this kind of definition

	def isRobotBounded(self, instructions:str) -> bool: