Python Brainf *** - Errors in Loops

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.

+5
source share
1 answer

I suppose the problem is your loop variable i , which you change during the loop:

 i += posOfEnd+1 

and

 i = posOfBegin 

However, python for loops are different from their C / C ++ counterparts. In python, the i variable will be set to every iterable element that you provide it, in this case range . range(n) evaluates a list containing all numbers from 0 to n-1 . If you change the loop variable during the iteration, then this modification remains only for this iteration, but the next iteration element will be assigned to the next loop iteration (without saving your changes).

Instead, you can use a while .

+5
source

Source: https://habr.com/ru/post/1262740/


All Articles