尽管2个变量中只有1个为真,但循环停止

时间:2016-11-07 22:00:00

标签: python python-3.x brainfuck

所以我试图制作一个Brainfuck解释器,但是在我用来执行Brainfuck循环的while循环中,即使只有一个条件成立,它也会爆发。

示例:

+++[>+<-]

应该导致:

[0, 3]

但是,当循环从[开始时,它将创建一个新单元格,因此结构从[3]变为[3, 0]。因此,当前工作单元格为0并且循环正在中断。但是,我只有在0且当前字符为]时才会中断。

cells = [0] # Array of data cells in use
brainfuck = str(input("Input Brainfuck Code: ")) # Brainfuck code
workingCell = 0 # Data pointer position
count = 0 # Current position in code
def commands(command):
    global cells
    global workingCell
    if command == ">":
        workingCell += 1
        if workingCell > len(cells) - 1:
            cells.append(0)
    elif command == "<":
        workingCell -= 1
    elif command == "+":
        cells[workingCell] += 1
    elif command == "-":
        cells[workingCell] -= 1
    elif command == ".":
        print(chr(cells[workingCell]))
    elif command == ",":
        cells[workingCell] = int(input("Input: "))
def looper(count):
    global cells
    global workingCell
    print("START LOOP", count)
    count += 1
    looper = loopStart = count
    while brainfuck[looper] != "]" and cells[workingCell] != 0: # This line is causing trouble
        if brainfuck[looper] == "]":
            looper = loopStart
        commands(brainfuck[looper])
        count += 1
        looper += 1
    return count
while count < len(brainfuck):
    if brainfuck[count] == "[":
        count = looper(count)
        print("END LOOP", count)
    else:
        commands(brainfuck[count])
    count += 1

提前谢谢。

1 个答案:

答案 0 :(得分:1)

我只有在0且当前字符为]

时才会中断

如果这就是您想要的,那么您while的逻辑错误。它应该是:

while not (brainfuck[looper] == "]" and cells[workingCell] == 0):

根据deMorgan's Laws,当您在not之间分发and时,您会反转每个条件并将and更改为or,因此它应该是:

while brainfuck[looper] != "]" or cells[workingCell] != 0:

如果这令人困惑,你可以写下:

while True:
    if brainfuck[looper] == "]" and cells[workingCell] == 0:
        break

这反映了你在描述中所说的内容。