我一直在研究BF解释器,试图确保它不使用外部库,并且在单个函数中工作.
我遇到的问题是某些程序运行良好,而其他程序则不然.这使得很难调试和计算以及出了什么问题.
常见的因素似乎是它无法处理带有多组括号的BF程序(虽然有一些例外,但是程序工作,但不完全).
代码:
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 = 1interpret(""" #This is where the BF code goes""")
我知道这不是最好的Python代码,我以为我会试一试.
有效的程序:
,----------[----------------------.,----------]
– 将小写转换为大写
[> > > > <<<<-]> .> . .. .> .<< .>. .------.--------.> .>.
– 你好,世界!
我目前正在努力完成的计划是:
[> > <<-]> >> <[-[>> <<-] >>]> [-<<<[->[ [-] > >>>-<<]<[<]>> [<< >>-] << .[-]<<]>.> [>>]> ]
它被设计为输出带有* s的Sierpinski三角形.
我没有输出,但如果我输出数组它似乎创建和几乎无穷无尽的序列0,1,0,1 ……等等.等等
从运行它通过一个正确的解释器我知道该数组应该只有120的长度,我在几秒钟内进入数千.
任何帮助,将不胜感激.
谢谢.
解决方法:
处理[和]时代码中存在一个错误:它们与正确的大括号不匹配,而是匹配最接近的大括号,如果忽略其中的所有大括号,包括其他大括号!这意味着你无法嵌套你的循环.我还在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 -= 1elif 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代码[i] ==’]’中保留if数组[pointerLocation] == 0: – 如果您关心性能,请阻止.如果这样做,则不需要在最后一行递减i.
品略图书馆 http://www.pinlue.com/