我一直在研究BF解釋器,試圖確保它不使用外部庫,并且在單個函數(shù)中工作. 我遇到的問題是某些程序運行良好,而其他程序則不然.這使得很難調(diào)試和計算以及出了什么問題. 常見的因素似乎是它無法處理帶有多組括號的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 = 1
interpret("""
#This is where the BF code goes
""")
我知道這不是最好的Python代碼,我以為我會試一試. 有效的程序: ,----------[----------------------.,----------]
– 將小寫轉(zhuǎn)換為大寫 [> > > > <<<<-]> .> . .. .> .<< .>. .------.--------.> .>.
– 你好,世界! 我目前正在努力完成的計劃是: [> > <<-]> >> <[-[>> <<-] >>]> [-<<<[->[ [-] > >>>-<<]<[<]>> [<< >>-] << .[-]<<]>.> [>>]> ]
它被設(shè)計為輸出帶有* s的Sierpinski三角形. 我沒有輸出,但如果我輸出數(shù)組它似乎創(chuàng)建和幾乎無窮無盡的序列0,1,0,1 ……等等.等等 從運行它通過一個正確的解釋器我知道該數(shù)組應(yīng)該只有120的長度,我在幾秒鐘內(nèi)進入數(shù)千. 任何幫助,將不勝感激. 謝謝. 解決方法: 處理[和]時代碼中存在一個錯誤:它們與正確的大括號不匹配,而是匹配最接近的大括號,如果忽略其中的所有大括號,包括其他大括號!這意味著你無法嵌套你的循環(huán).我還在python中編寫了一個bf解釋器,我使用了一個計數(shù)器變量open_braces,它從1開始,并通過向搜索方向打開的大括號遞增,并通過關(guān)閉到搜索方向的大括號遞減.修復(fù)您的代碼如下: 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代碼[i] ==’]’中保留if數(shù)組[pointerLocation] == 0: – 如果您關(guān)心性能,請阻止.如果這樣做,則不需要在最后一行遞減i. 來源:https://www./content-1-258751.html
|