我试图根据语法规则制作代码来识别一串字符:
这样的话就像 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']))
答案 0 :(得分: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]