我是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
将设置为您提供它的迭代的每个元素,在本例中range
.range(n)
评估到包含0
最多的所有数字的列表n-1
.如果在迭代期间修改循环变量,则此修改仅保留用于该迭代,但是对于下一次迭代,循环变量将被分配迭代的下一个元素(不保留您的修改).
您可能希望使用while
循环.