Reputation: 13
I'm brand new to programming and have been working on a free Python course from the University of Waterloo. I'm currently stuck on Section 15A, where I have to write a BASIC simulator. I'm working on the section titled "Smart Simulation", where I'm writing the code to execute the BASIC program.
Part of the exercise is having to determine if the program completed successfully, or if it entered an infinite loop. Here is the current code I have for this section:
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
So I've run this code through their Python visualizer, and the problem I'm having is that it is return infinite loop
when it should be returning success
. Their automated grader has, so far, tested my code with the following two inputs:
execute(['10 GOTO 21', '21 GOTO 37', '37 GOTO 21', '40 END'])
which results in the correct answer of "infinite loop", but the second input of execute(['5 GOTO 30', '10 GOTO 20', '20 GOTO 10', '30 GOTO 40', '40 END'])
is also returning "infinite loop", though it should return "success".
There may be better ways to determine if the program is looping, but I've followed the hints the course has given me for setting it up, and I'd like to be able to complete it the way they expect me to. I seriously appreciate any input anyone might have for this! I've been stuck on this and experimenting for some time and I'm pulling my hair out because I just can't figure out what to do to make it work. Thanks for any help that's offered! :)
Upvotes: 1
Views: 347
Reputation: 5261
The problem is in the lines
location = findLine(prog, T)
visited[location] = True
You're marking the new location
as visited before you test it at the top of the loop. Just change the order of these two lines. Mark the current location
as visited before you update to the new location
.
Upvotes: 0
Reputation: 671
You almost did it!
you just misplaced the assignment order, it should be like:
T = currentLine[2]
visited[location] = True
location = findLine(prog, T)
Upvotes: 1