2016-09-29 156 views
0

我試圖做一個代碼來識別以下語法規則字符的鏈條:Python代碼接受預先定義的語法

  • S-> ABK
  • K-> X | XK | ħ
  • H-> C^| d

使字狀ABXabxxxABCabxdabxc,等等...都接受的話就像ABABBXXX,等等是不能接受的。

我寫了一個代碼來做到這一點,在我的分析中,它應該做的伎倆,但它有錯誤,即它返回假的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'])) 
+3

「*,但也有一些是錯誤的它*」 < - 請詳細說明 –

+3

我注意到你有一行'K(atual,word)',這個函數運行這個函數,但是對返回值沒有做任何事情,然後返回None,我認爲這是問題,但不能確定沒有詳細說明。另外,我建議通過它[一步一步在可視化](http://www.pythontutor.com/visualize.html#mode=edit) –

+0

感謝@ TadhgMcDonald-Jensen我發現了什麼是錯的,它是你指出的那一行,我只需要寫「return K(atual,word)」 –

回答

1

你的實現是不必要的冗長和重複的:沒有必要繞過指數,例如,當你可以傳遞給下一個函數字的相關部分。這裏是一個快速的實現我扔在一起,應該可以解決它:

def S(chars): 
    word = ''.join(chars) 
    try: 
    return word[:2] == 'ab' and K(word[2:]) 
    except IndexError: 
    return False 

def K(word): 
    return word == 'x' or (word[0] == 'x' and K(word[1:])) or H(word) 

def H(word): 
    return word in ['c', 'd'] 

使用此功能,我得到:

>>> list(map(S, ['abx', 'abxxx', 'abc', 'abxd', 'abxc'])) 
[True, True, True, True, True] 
+0

OP的函數能夠處理一個字符列表作爲輸入,其中你的實現只在傳遞字符串時才起作用。雖然我認爲使用字符串更有意義 - 它不適用於OP目前如何使用它。 –

+0

@brianpck你的代碼非常出色。恭喜你。我也瞭解它,並在一些測試中,我已經做到了 –