2016-11-05 93 views
1

我是编程的新手,并且一直在从滑铁卢大学学习一门免费的Python课程。我目前卡在Section 15A,我必须编写一个BASIC模拟器。我正在编写题为“智能模拟”的部分,我正在编写执行BASIC程序的代码。Python BASIC模拟器

练习的一部分是确定程序是否成功完成,或者是否进入无限循环。下面是当前代码我有本节:

def findLine(prog, target): 
    for x in range(0,len(prog)): 
     prog2 = prog[x].split() 
     start = prog2[0] 
     if len(prog2) > 2: 
     end = prog2[2] 
     if start == target: 
     return x 


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

所以我通过自己的Python可视化运行这段代码,和我遇到的问题是,它是返回infinite loop当它应该返回success。他们的自动平地机,到目前为止,测试我的代码有以下两个输入:

execute(['10 GOTO 21', '21 GOTO 37', '37 GOTO 21', '40 END'])导致的“无限循环”的正确答案,但execute(['5 GOTO 30', '10 GOTO 20', '20 GOTO 10', '30 GOTO 40', '40 END'])第二输入还返回“无限循环”,虽然它应该返回“成功”。

可能有更好的方法来确定程序是否循环,但我已经按照课程给予我的设置提示,我希望能够按照他们期望的方式完成它至。我非常感谢任何人为此付出的任何投入!我一直坚持这一点,并试验了一段时间,我把我的头发拉出来,因为我无法弄清楚如何使它发挥作用。感谢您提供的任何帮助! :)

+0

我想这是因为你用'while True:'。你必须使用while而不是location == len(prog)-1',并且在循环结束后你可以执行print('success')或者print'success'(对于Python 3和2)。告诉我,如果我不正确。 – MaxLunar

回答

1

你几乎做到了!

你只是放错了地方的分配顺序,应该是这样的:

T = currentLine[2] 
    visited[location] = True 
    location = findLine(prog, T) 
+0

非常感谢你!修正这个命令使我的代码工作,并通过了练习。你们是最棒的! – Ryan

+0

欢迎您;) –

0

的问题是在线路

location = findLine(prog, T) 
    visited[location] = True 

你标记为已访问你测试它在之前的新location循环的顶部。只要改变这两行的顺序即可。在更新到新的location之前,将当前的location标记为已访问。