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

我是python的初学者,为了增强我的技能,我(尝试)为Brainfu **语言编写一个编译器.一切都很好,除了括号[]循环.我用来测试我的代码的程序是> [&GT &LT – &GT ,应该将单元格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将被设置为您提供它的迭代的每个元素,在本例中为范围. range(n)计算到包含从0到n-1的所有数字的列表.如果在迭代期间修改循环变量,则此修改仅保留用于该迭代,但是对于下一次迭代,循环变量将被分配迭代的下一个元素(不保留您的修改).

您可能希望使用while循环.

上一篇:如何在Python中构建Brainfuck解释器?


下一篇:不仅仅是base-WP