在Python中解析Brainfuck括号时遇到问题

时间:2018-08-24 11:36:42

标签: python brainfuck

我正在使用该语言练习Python中的Brainfuck编译器。大多数符号并没有太大的挑战,但是我绝对对[]感到困惑。

这是我到目前为止所拥有的

global cells
global pointer
cells = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
pointer = 0

#bfcode = list(input())
bfcode = list("+x+++,[>++++<-]>.")
for i in range(len(bfcode)):
    if(bfcode[i] == "."):
        print(cells[pointer])
    elif(bfcode[i] == ","):
        charin = list(input("Write one character: "))[0]
        cells[pointer] = ord(charin)
    elif(bfcode[i] == "+"):
        cells[pointer] += 1
    elif(bfcode[i] == "-"):
        cells[pointer] -= 1
    elif(bfcode[i] == ">"):
        pointer += 1
    elif(bfcode[i] == "<"):
        pointer -= 1
    elif(bfcode[i] == "["):
        print("PLACEHOLDER")
    elif(bfcode[i] == "]"):
        print("PLACEHOLDER")
    else:
        print("Non-brainfuck character detected")
    print(cells)

因此,作为Python新手,我的第一个直觉是以某种方式在for循环中倒退,但据我所知,这在Python中是不可能的。我已经搜索了循环返回的解决方案,但目前所有这些解决方案都超出了我的理解范围...

是否有一种简单的方法可以让我以某种方式错过的for循环向后退?或者,也许有一种更简单的方法可以一起完成所有这些工作?

我的代码的其他提示和建议也非常感谢,因为我还在学习:)

1 个答案:

答案 0 :(得分:0)

这就是我所做的:

elif ins == '[':
                # only does stuff if memory isnt zero
                if mem[ptr] == 0:
                    # initialistation
                    count = 0
                    ic += 1
                    # keeps going until the end of the program
                    while ic <= len(self.prg):
                        # sets instruction
                        ins = self.prg[ic]
                        # if has found the matching bracket, it ends
                        if ins == ']' and count == 0:
                            break
                        # deals with nested loops
                        elif ins == '[':
                            count += 1
                        elif ins == ']':
                            count -= 1
                        # moves forward one place in the program
                        ic += 1
            # its an algorithim, dont ask
            elif ins == ']':
                # only does stuff if memory is zero
                if mem[ptr] != 0:
                    # initialistation
                    count = 0
                    ic -= 1
                    # keeps going until the end of the program
                    while ic >= 0:
                        # sets instruction
                        ins = self.prg[ic]
                        # if has found the matching bracket, it ends
                        if ins == '[' and count == 0:
                            break
                        # deals with nested loops
                        elif ins == ']':
                            count += 1
                        elif ins == '[':
                            count -= 1
                        # moves backward one place in the program
                        ic -= 1

它可能与您使用的结构不同,但是应该给您一些想法。

简而言之,您将遍历代码,找到一个括号时加一,找到一个括号时减一,以找到匹配的括号。