设有文法GAA→iBeB→SBS→eCiC→eCe编写一个递归下降分析程序对给定的单词序列判断其是否符合该文法的要求?如果是输出Success否则输出Error。输入格式:一个字符串为单词序列每个符号为一个单词输出格式:Success或者Error。
以下是Python3代码:
def match(ch):
global i, s
if i < len(s) and s[i] == ch:
i += 1
return True
return False
def A():
if match('i'):
if B():
if match('*'):
if match('e'):
return True
return False
def B():
if S():
if B():
return True
elif match('e'):
return True
return False
def S():
if match('['):
if match('e'):
if C():
if match(']'):
return True
elif match('.'):
if match('i'):
return True
return False
def C():
if match('e'):
if C():
return True
elif match('e'):
return True
return False
s = input().strip()
i = 0
if A() and i == len(s):
print('Success')
else:
print('Error')
其中,match函数表示匹配单词,A、B、S、C分别对应文法中的四个非终结符,递归下降分析程序按照文法规则进行匹配。如果最终匹配成功且所有单词均被匹配,则输出“Success”,否则输出“Error”
原文地址: https://www.cveoy.top/t/topic/hmYu 著作权归作者所有。请勿转载和采集!