I am a relative newbie to python, and in order to strengthen my skills, I am (trying) to write a compiler for Brainfu** . Everything is fine, except for the brackets [] . The program I use to test my code is >++[>++<-]>+ , which should set the cell from 2 to 5. However, when I run this, it does this:
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]
(Lines are formatted in an iteration, then a list at that point, then the value it focuses on, and then the character it works with.)
My current code
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 tries to figure out where the next bracket is, and posOfBegin tries to find out where the previous bracket is.