gpt4 book ai didi

Python BASIC 模拟器

转载 作者:太空宇宙 更新时间:2023-11-03 15:59:53 24 4
gpt4 key购买 nike

我是编程新手,一直在研究滑铁卢大学的免费 Python 类(class)。我目前陷入 Section 15A ,我必须在那里编写一个 BASIC 模拟器。我正在研究标题为“智能模拟”的部分,我正在编写代码来执行 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 可视化工具运行了这段代码,我遇到的问题是,当它应该返回成功时,它却返回无限循环。到目前为止,他们的自动评分器已使用以下两个输入测试了我的代码:

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']) 的第二个输入也返回“无限循环” ”,尽管它应该返回“成功”。

可能有更好的方法来确定程序是否正在循环,但我已经按照类(class)给我的提示进行了设置,并且我希望能够按照他们期望的方式完成它。我非常感谢任何人为此提供的任何意见!我已经坚持这个问题并尝试了一段时间,但我正在抓狂,因为我就是不知道该怎么做才能让它发挥作用。感谢您提供的任何帮助! :)

最佳答案

你几乎做到了!

你刚刚放错了分配顺序,它应该是这样的:

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

关于Python BASIC 模拟器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40440056/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com