我試圖做一個代碼來識別以下語法規則字符的鏈條:Python代碼接受預先定義的語法
- S-> ABK
- K-> X | XK | ħ
- H-> C^| d
使字狀ABX,abxxx,ABC,abxd,abxc,等等...都接受的話就像AB,ABB,XXX,等等是不能接受的。
我寫了一個代碼來做到這一點,在我的分析中,它應該做的伎倆,但它有錯誤,即它返回假的abxx,一個語法應接受的句子,我認爲它與函數的嵌套返回值有關,我不太清楚。
代碼將被粘貼在下面,如果你們可以弄清楚或指出我在做什麼錯我會很感激。
def S(word):
if word[0] == 'a':
atual = 1
else:
return False
if word[1] == 'b':
atual = 2
else:
return False
accepted = K(atual, word)
if accepted == True:
return True
else:
return False
def K(atual, word):
if word[atual] == 'x':
atual += 1
if len(word) <= atual: # checks to see if the word ended and accept by the first rule of the set K.
return True
else:
K(atual, word) # keeps increasing the value of atual, satisfying the rule xK
else:
value = H(atual, word) # if no more 'x' are found, try the rule H
return value
def H(atual, word):
if word[atual] == 'c' or word[atual] == 'd':
return True
else:
return False
print(S(['a','b','x','x']))
「*,但也有一些是錯誤的它*」 < - 請詳細說明 –
我注意到你有一行'K(atual,word)',這個函數運行這個函數,但是對返回值沒有做任何事情,然後返回None,我認爲這是問題,但不能確定沒有詳細說明。另外,我建議通過它[一步一步在可視化](http://www.pythontutor.com/visualize.html#mode=edit) –
感謝@ TadhgMcDonald-Jensen我發現了什麼是錯的,它是你指出的那一行,我只需要寫「return K(atual,word)」 –