2017-01-13 41 views
5

我是一个相对的Python初学者,为了加强我的技能,我(试图)编写Brainfu**语言的编译器。一切都很好,除了支架[]循环。我使用的测试我的代码的程序是>++[>++<-]>+,这应该设置小区2至5。当我运行这一点,但是,它这样做:Python Brainf *** - 在while循环上的错误

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试图找出预先的位置vious括号是。

+2

看起来像python遍历范围(0,len(chars))''就像你告诉它的那样。在循环中修改'i'不起作用。 – melpomene

回答

5

我想这个问题是你的循环变量i您在循环过程中修改:

i += posOfEnd+1 

i = posOfBegin 

然而蟒蛇for循环是从他们的C/C++的同行不同。在Python中,变量i将被设置为您提供它的迭代器的每个元素,在这种情况下为rangerange(n)评估的列表包含0n-1之间的所有数字。如果在迭代过程中修改循环变量,那么此修改仅保留该迭代,但对于下一次迭代,循环变量将分配迭代的下一个元素(不保留修改)。

您可能需要改用while循环。