gpt4 book ai didi

python - 如何在 Python 中构建一个 Brainfuck 解释器?

转载 作者:太空狗 更新时间:2023-10-30 02:54:36 25 4
gpt4 key购买 nike

我一直在研究 BF 解释器,试图确保它不使用外部库,并在单个函数中工作。

我遇到的问题是一些程序运行良好,而另一些则不能。这使得调试和找出问题所在变得困难。

共同点似乎是它无法处理多于一组括号的 BF 程序(尽管有一些异常(exception),但随后程序可以工作,只是不完全)。

代码:

def interpret(code):
array = [0]
pointerLocation = 0
i = 0
c = 0
print(code)
while i < len(code):
if code[i] == '<':
if pointerLocation > 0:
pointerLocation -= 1
elif code[i] == '>':
pointerLocation += 1
if len(array) <= pointerLocation:
array.append(0)
elif code[i] == '+':
array[pointerLocation] += 1
elif code[i] == '-':
if array[pointerLocation] > 0:
array[pointerLocation] -= 1
elif code[i] == '.':
print(array[pointerLocation], chr(array[pointerLocation]))
elif code[i] == ',':
x = input("Input:")
try:
y = int(x)
except ValueError:
y = ord(x)
array[pointerLocation] = y
elif code[i] == '[':
if array[pointerLocation] == 0:
while code[i] != ']':
i += 1
elif code[i] == ']':
if array[pointerLocation] != 0:
while code[i] != '[':
i -= 1
i += 1
interpret("""
#This is where the BF code goes
""")

我知道这不是最好的 Python 代码,我只是想试一试。

有效的程序:

,----------[----------------------.,----------]  

- 将小写字母转换为大写字母

++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.

- 你好,世界!

我目前正在尝试运行的程序是:

++++++++[>+>++++<<-]>++>>+<[-[>>+<<-]+>>]>+[-<<<[->[+[-]+>++>>>-<<]<[<]>>++++++[<<+++++>>-]+<<++.[-]<<]>.>+[>>]>+]

它被设计用来输出带有 *s 的 Sierpinski 三角形。

我没有得到任何输出,但如果我输出数组,它似乎创建了几乎无穷无尽的有序数组 0、1​​、0、1......等等。等

通过适当的解释器运行它,我知道数组的长度应该只有 120,而我在几秒钟内就达到了数千。

如有任何帮助,我们将不胜感激。

谢谢。

最佳答案

您的代码在处理 [] 时存在错误:它们不匹配正确的大括号,而是匹配最接近的大括号,可以 fit if everything between are ignored including other braces!!! 这意味着你不能嵌套你的循环。我还在 python 中编写了一个 bf 解释器,我使用了一个计数器变量 open_braces,它从 1 开始,随着大括号向搜索方向打开而递增,并随着大括号向搜索方向关闭而递减。按如下方式修复您的代码:

elif code[i] == '[':
if array[pointerLocation] == 0:
open_braces = 1
while open_braces > 0:
i += 1
if code[i] == '[':
open_braces += 1
elif code[i] == ']':
open_braces -= 1
elif code[i] == ']':
# you don't need to check array[pointerLocation] because the matching '[' will skip behind this instruction if array[pointerLocation] is zero
open_braces = 1
while open_braces > 0:
i -= 1
if code[i] == '[':
open_braces -= 1
elif code[i] == ']':
open_braces += 1
# i still gets incremented in your main while loop
i -= 1

请注意,如果您愿意,可以在 elif code[i] == ']': block 中保留 if array[pointerLocation] == 0关于性能。如果这样做,则不需要在最后一行中递减 i。

关于python - 如何在 Python 中构建一个 Brainfuck 解释器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45240788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com