Python 3 - BASIC Simulator

∥☆過路亽.° 提交于 2019-12-12 02:24:43

问题


I'm currently working on a BASIC simulator in Python, as the title suggests. This program should either print "success" or "infinite loop", depending on which one is true. Here is my code:

def findLine(prog, target):
   for l in range(0, len(prog)):
      progX = prog[l].split()
      if progX[0] == target:
          return l 

def execute(prog):
  location = 0
  while True:
    if location==len(prog)-1: return "success"
    else: return "infinite loop"
    T = prog.split()[location]
    location = findLine(prog, T)

FindLine should take an input like this: findLine(['10 GOTO 20', '20 END'], '20') and output the index of prog in which target appears.
execute should take an input like this: execute(['10 GOTO 21', '21 GOTO 37', '37 GOTO 21', '40 END'])

Problem is, the "def execute(prog)" portion of this code is broken, and I need some help fixing it so it does what I describe earlier. Any help with debugging this would be appreciated, and apologies if this is a little vague -- I'm not quite sure what to write.


回答1:


You should try to execute your code step by step in a debugger to see what happens. Or just do it mentally.

First, you set location to 0. Then, you look if it is equals to the number of lines. If so, you return success, if not, you return infinite loop. How to you expect the next two lines to be executed?

I think you should redesign the way you detect an infinite loop. Not being currently on the last line isn't a sufficient condition... If you interpreter only handles GOTO, then reaching the same line two times could be a good hint. But if you implement more logic, then you should think about detecting the number of times you reach each line, and set a threshold on that.



来源:https://stackoverflow.com/questions/15832517/python-3-basic-simulator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!