私はロボットの動きを刺激する問題を解決しようとしています。ロボットは位置(0、0、 'N')で始まります。コマンドは文字列のリストで与えられます。 'turn'関数はNからE、SからW、そしてNに戻ります。移動関数は特定の方向に移動します.N、Sはy軸、E、Wはx軸です。 N:y + 1 S:y-1 W:x-1 E:x + 1Pythonでの再帰の使い方
機能にショートカットを使用しようとすると、困っている部分があります。
print(macro_interpreter(['turnleft', 'turnright'], {'turnleft': ['turn', 'turn', 'turn'], 'turnright' : ['turn'], 'bigleftturn' : ['move', 'move', 'turnleft', 'move', 'move'], 'bigrightturn' : ['move', 'move', 'turnright', 'move', 'move']}))
の定義:代わりに 'ターン'
def macro_interpreter(code, macros):
の 'turnleft' の代わりの[ 'ターン'、 'ターン'、 'ターン'] 'turnright' を使用すると、ときに関数を呼び出しますその用語は辞書で与えられる。 私のコードは、最初のコマンドのために実行し、その後終了し、それがリスト
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])
期待される出力は?私の 'turn'があなたのマクロ(2回目の実行時)に存在せず、' move''も返されたコードの一部ではないので、そのブロックの下の他の条件は決して実行されません。また、数値をインクリメントすると、IndexErrorが発生することはなく、欠落しているインデックスのリストにアクセスしようとします。 – danidee