繁体   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