2016-10-15 3 views
1

로봇의 움직임을 자극하는 문제를 해결하려고합니다. 로봇은 위치 (0, 0, 'N')로 시작합니다. 명령은 문자열 목록에 제공됩니다. '회전'기능은 N에서 E에서 S에서 W로 회전하여 N으로 돌아갑니다. 이동 기능은 특정 방향 (N 축, Y 축, E 축, W 축)으로 이동합니다. N : y + 1 S : y-1 W : x-1 E : x + 1파이썬에서 재귀를 사용하는 방법

문제가있는 부분은 기능에서 바로 가기를 사용하려고 할 때입니다.

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])    
+0

예상되는 출력은 무엇입니까? 까지 내가 볼 수있는'턴'은 매크로 (두 번째 실행)에 존재하지 않으며''이동 '은 반환 된 코드의 일부가 아니므로, 그 블록 아래의 다른 조건은 절대 실행되지 않습니다 .. .. 그리고 또한 숫자를 증가 시키면'IndexError'가 발생하지 않을 것입니다. 누락 된 인덱스가있는 목록에 액세스하려고하면됩니다. – danidee

답변

0

return macro_interpreter (macros etc. 

그냥 할 것입니다 라인에서 두 번째 코드를 무시합니다. for 루프를 끝내고 외부 호출에서 돌아옵니다. 이야기의 끝.

2

code 명령을 통해 항상 루프의 else 문을 누르는 경우 command not in macros이 표시되므로 절대로 다시 실행되지 않습니다. 좀 더 정확하게이 작업을 수행하려면, 당신은 X, Y를 전달할 수 있으며, "방향 인덱스 상태"와 같은 경우 첫 번째 반복 후

, code == ['turn', 'turn', 'turn']하지만 macros는 더 키 "turn"


포함되어 있지 않습니다 매개 변수를 함수에 추가 한 다음 함수의 로컬 변수를 수정하기보다는 재귀 호출 내에서 해당 변수를 증가/수정하고 항상 (0,0, 0)에서 다시 시작하십시오.

또한, 당신은 더 IndexError 내가 그것 때문에 용의자이

state = ['N', 'E', 'S', 'W'] 
def macro_interpreter(code, macros, x=0,y=0,index=0): 
    # TODO: check if x or y have gone outside "the board" 
     # TODO: return to break from recursion 

    for command in code: 
     if command in macros: 
      return macro_interpreter(macros[command], macros,x,y,index) 
     else: 
      if command == 'move': 
       if state[index] == 'N': 
        return macro_interpreter(code[1:], macros,x,y=y+1,index) 
0

처럼


그래서 어떤 수를 증가시켜 잡힐 것 없기 때문에 그 index = (index + 1) % len(state)있는 경우를 제외하고 시도 교체해야 당신은 돌아갑니다

macro_interpreter(macros[command], macros) 

이것은 단순히 functi를 종료합니다. 한번 반복 된 코드가 실행됩니다. 당신이 코드는 당신이 수행 할 작업을 인쇄 할 것을

print macro_interpreter(macros[command], macros) 

return macro_interpreter(macros[command], macros) 

을 변경 여부를 알 수 있습니다. 출력을 실제로 처리하는 방법은 귀하에게 달려 있습니다.

1

재귀를 올바르게 지원하기 위해 귀하의 코드에서 수정 한 몇 가지 수정 사항이 있습니다. 이 코드는 당신이 원하는 것을 달성 할 것입니다.이제

def macro_interpreter(code, macros, x=0, y=0, index=0): 
    state = ['N', 'E', 'S', 'W'] 
    for command in code: 
     if command in macros: 
      x, y, curr_state = macro_interpreter(macros[command], macros, x, y, index) 
      # update new index with new state value   
      index = state.index(curr_state) 
     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':     
       index = (index + 1)%len(state) 
    return (x, y, state[index]) 

, 당신의 테스트 케이스

>> print macro_interpreter(['turnleft', 'turnright'], {'turnleft': ['turn', 'turn', 'turn'], 'turnright' : ['turn'], 'bigleftturn' : ['move', 'move', 'turnleft', 'move', 'move'], 'bigrightturn' : ['move', 'move', 'turnright', 'move', 'move']}) 
Output:- (0, 0, 'N') 

실행하면 나는이 의지가 당신을 도움이되기를 바랍니다.

관련 문제