返回无限循环python成功

时间:2015-08-31 07:44:55

标签: python loops

我在线学习Python,但不明白我应该采取的最后一步。

这是问题

编写函数execute(prog)来执行以下操作。假设prog是包含BASIC程序的字符串列表,就像之前一样。然后,您的函数应返回"success" or "infinite loop",具体取决于程序是否终止,或永久循环。重要提示:您应该假定已经定义了子任务2中定义的过程findLine(prog, target),您不需要重新编写它。提示

输入示例:(['5 GOTO 30', '10 GOTO 20', '20 GOTO 10', '30 GOTO 40', '40 END'])

我的代码在返回成功时仍会返回"infinite loop",但我找不到最后一步所需的步骤。 (我也在这里包括我所有的调试检查)

def execute(prog):
  location = 0
       #print('prog = ', prog)
  visited = [False] * len(prog)

  while True:
     for i in range (0,len(prog)):
        visited[i] = True  
      #print('prog is type=',type(prog))
      # print(type(location))
      #print('len of prog=', len(prog))
      #for i in range (0,len(prog)):
       #  visited[i] = True  
      #   print('visited =', visited)
       #  print('visited[i] =', visited[i])
        # print('prog[i] =', prog[i])     
  findT = prog[location].split()
      #print('findT = ',findT)
  T = findT[-1]
      #print('T=',T)
  location = findLine(prog, T)
      #print('new location=', location)
  if visited[location]:
     return "infinite loop"
  elif location==len(prog)-1: 
     return "success"
         #print('T=',T)
      #print('prog = ', prog)

提示:这是我编写并运作的getBASIC()和findline()代码:

def getBASIC():
   myList = []
   while True:
      line = str(input())
      myList.append(line)
      if line.endswith("END"):
        break
   return myList


def findLine(prog, target):
   for i in range(0, len(prog)):  #range doesn't include last element.
     progX = prog[i].split()
     if progX[0] == target:
          return i 

1 个答案:

答案 0 :(得分:0)

这是您正确的代码版本:

def execute(prog):
    location = 0
    counter = 0
    while True:
        findT = prog[location].split()
        T = findT[-1]
        location = findLine(prog , T)
        counter += 1
        if T == 'END':
            return "success"
        if counter > len(prog):
            return "infinite loop"

在这种情况下,使用简短的方法和简便的解决方案:)