簡體   English   中英

接受預定義語法的Python代碼

[英]Python code to accept pre-defined grammar

我正在嘗試按照語法規則編寫代碼以識別字符鏈:

  • S-> abK
  • K-> x | xK | H
  • 高度

因此,諸如abxabxxxabcabxdabxc等之類的詞均被接受,而諸如ababbxxx等之類的詞則不被接受。

我寫了一個代碼來做到這一點,並且在我的分析中它應該可以解決這個問題,但是其中有些問題,即,對於abxx,它返回False,這是語法應該接受的句子,我認為這與從函數嵌套的返回值,我不太了解。

該代碼將粘貼在下面,如果你們能弄清楚或指出我做錯了什么,我將非常感激。

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']))

您的實現不必要地冗長和重復:例如,無需傳遞索引,例如,您可以僅將單詞的相關部分傳遞給下一個函數。 這是我提出的快速解決方案,可以解決該問題:

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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM