I am trying to solve a problem which stimulate movements of a robot. The robot starts with position (0, 0, 'N'). The command is given in a list of strings. the 'turn' function turns from N to E to S to W and back to N. The move function moves in the specific direction: N,S in y axis and E,W in x axis. N: y+1 S: y-1 W: x-1 E: x+1
The part I am having trouble with is, when trying to use shortcuts in the function. Using 'turnleft' instead of ['turn', 'turn', 'turn'], 'turnright' instead of 'turn'
def macro_interpreter(code, macros):
when call the function:
print(macro_interpreter(['turnleft', 'turnright'], {'turnleft': ['turn', 'turn', 'turn'], 'turnright' : ['turn'], 'bigleftturn' : ['move', 'move', 'turnleft', 'move', 'move'], 'bigrightturn' : ['move', 'move', 'turnright', 'move', 'move']}))
the definition of the term is given in a dictionary. My code only runs for the first command and then terminate, it ignores the second code in the list
def macro_interpreter(code, macros):
x,y,index = 0, 0, 0
state = ['N', 'E', 'S', 'W']
for command in code:
if command in macros:
return macro_interpreter(macros[command], macros)
else:
if command == 'move':
if state[index] == 'N':
y += 1
elif state[index] == 'E':
x += 1
elif state[index] == 'S':
y -= 1
elif state[index] == 'W':
x -= 1
elif command == 'turn':
try:
index = index + 1
except IndexError:
index = 0
return (x, y, state[index])
turnisn't present in your macro's (on the second run) and'move'wasn't part of the codes returned also, so the other conditions under that block will never run....and also incrementing a number would never raise anIndexError, rather trying to access a list with a missing index would.