程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

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

发布于2019-11-11 14:19     阅读(491)     评论(0)     点赞(19)     收藏(2)


我是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,在这种情况下,变量将设置为您提供的iterable的每个元素rangerange(n)计算得出一个包含从0到的所有数字的列表n-1如果您在迭代过程中修改了循环变量,则此修改仅适用于该迭代,但对于下一次迭代,将为循环变量分配可迭代对象的下一个元素(不保留您的修改)。

您可能要使用while循环。



所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:https://www.pythonheidong.com/blog/article/150192/00eaddef97969bbf7a3c/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

19 0
收藏该文
已收藏

评论内容:(最多支持255个字符)