Python Brainf*** – while 循环中的错误

标签 python brainfuck

我是 python 的初学者,为了加强我的技能,我正在(尝试)为 Brainfu** 编写一个编译器。语言。一切都很好,除了支架[]循环。我用来测试代码的程序是 >++[>++<-]>+ ,它应该将单元格 2 设置为 5。但是,当我运行它时,它会这样做:

0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 0 >
1 [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 1 +
2 [0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 2 +
3 [0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 2 [
4 [0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 0 >
5 [0, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 1 +
6 [0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 2 +
7 [0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 2 <
8 [0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 1 -
3 [0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 1 [
10 [0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 2 >
11 [0, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 3 +
[0, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

(行在迭代中被格式化,然后是那个点的列表,然后是它关注的值,然后是它运行的字符。)

我当前的代码是

def generateArray(code):
    array = []
    for i in range(0,20):
        array.append(0);
    return array

def run(code):
    print code
    data = generateArray(code)
    chars = list(code)
    pointer = 0

    for i in range(0, len(chars)):
        current = chars[i]
        if(current == "+"):
            data[pointer] += 1

        if(current == ">"):
            pointer += 1

        if(current == "-"):
            data[pointer] -= 1

        if(current == "<"):
            pointer -= 1

        if(current == "."):
            print str(chr(data[pointer]))

        if(current == ","):
            given = raw_input()
            data[pointer] = ord( given )

        if(current == "["):
            posOfEnd = chars[i:len(chars)].index("]")
            if(data[pointer] == 0):
                i += posOfEnd+1

        if(current == "]"):
            posOfBegin = len(chars) - 1 - chars[::-1].index('[')
            i = posOfBegin



        print i, data, data[pointer], chars[i]

    return data

print run(">++[>++<-]>+")

posOfEnd试图找出下一个括号在哪里,posOfBegin正在尝试找出前一个括号的位置。

最佳答案

我想问题出在你的循环变量 i 上,你在循环中修改了它:

i += posOfEnd+1

i = posOfBegin

但是 python for 循环不同于它们的 C/C++ 对应物。在 python 中,变量 i 将设置为您提供的可迭代对象的每个元素,在本例中为 rangerange(n) 的计算结果为包含从 0n-1 的所有数字的列表。如果您在迭代期间修改循环变量,则此修改仅保留该迭代,但对于下一次迭代,循环变量将分配给可迭代对象的下一个元素(不保留您的修改)。

您可能想改用 while 循环。

关于Python Brainf*** – while 循环中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41635379/

相关文章:

while-loop - 在 Brainfuck 中将一个数字的倍数放入细胞中的更好方法?

ascii - 脑残乘法

if-statement - 谁能解释为什么这个 brainfuck if/else 代码不起作用?

brainfuck - Brainfuck 中的无限计数循环

Python Tkinter返回csv文件目录

python - 按列值连接两个数据框

python - Numpy for windows安装问题

python - 如果满足特定条件,则将字符串与列表列表连接起来

python - 如何在 Python 中构建一个 Brainfuck 解释器?

python - 选择 "other value"的通用方法