循环停止,即使2个变量中只有1个是tru

2024-05-18 17:42:30 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我正在尝试做一个Brainfuck解释器,但是在我用来执行Brainfuck循环的while循环中,即使只有一个条件是真的,它还是会爆发。在

示例:

+++[>+<-]

应导致:

^{pr2}$

但是,当循环从[开始时,它将创建一个新的单元格,以便结构从[3]变为{}。因此,当前的工作单元是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

提前谢谢你。在


Tags: ininputifcountglobalcommandcommandsprint
1条回答
网友
1楼 · 发布于 2024-05-18 17:42:30

我只有在它是0并且当前字符是]

如果这是你想要的,你的while中的逻辑是错误的。它应该是:

^{1}$

根据deMorgan's Laws,当你把not分布在and上时,你把每个条件都颠倒,把and改成{},所以它应该是:

^{pr2}$

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

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

这正是你在描述中所说的。在

相关问题 更多 >

    热门问题