I am trying to write a solution to the following problem using as few characters as possible (to meme my friend and introduce him to golfing). Can any improvements be done to my code?
So the problem requires us to write a function called navigate
in Python 3.6 (language of the judge, sorry, no walruses) that takes two arguments:
- the first is a list of strings called "commands", which can be chosen from the following:
Drive
,TurnL
,TurnR
- the second is a tuple of three element, the first two are integers describing, respectively, the
x
andy
coordinates of a "car", and the third element of the tuple is a single-character string chosen out ofN
,E
,S
andW
, describing the direction which the car is facing initially
and returns a tuple with the same format as the second argument, which denotes the final coordinates and orientation of the car.
The commands are defined as follows (I tried to make them rigorous):
TurnL
: change the orientation of the car with the following map:f:{N->W->S->E->N}
TurnR
: change the orientation of the car with the inverse off
Drive
: increment or decrement the value ofx
ory
by 1, depending on the current orientation (see below table)
orientation | change in x |
change in y |
---|---|---|
N | 0 | 1 |
E | 1 | 0 |
S | 0 | -1 |
W | -1 | 0 |
My current progress is 189 Bytes:
N,E,S,W='NESW'
def navigate(c,s):
x,y,d=s
for i in c:
if i[4]=='L':d={N:W,W:S,S:E,E:N}[d]
elif i[4]=='R':d={N:E,E:S,S:W,W:N}[d]
else:x+=(d==E)-(d==W);y+=(d==N)-(d==S)
return x,y,d
I do not think typing out the long word "navigation" is avoidable. However, although the question asks for an implementation of a function, I do believe any callable, including anonymous functions, methods, etc., would be accepted.
Below is a test case
>>> navigate(['Drive', 'TurnR', 'Drive'], (0, 0, 'E'))
(1, -1, 'S')