FIRST = {}
FOLLOW = {}
sentences = [
'E->TG',
'G->+TG',
'G->-TG',
'G->ε',
'T->FS',
'S->*FS',
'S->/FS',
'S->ε',
'F->(E)',
'F->i',]
def initail():
for str in sentences :
part_begin = str.split("->")[0]
part_end = str.split("->")[1]
FIRST[part_begin] = ""
FOLLOW[part_begin] = "#"
def getFirst():
for str in sentences:
part_begin = str.split("->")[0]
part_end = str.split("->")[1]
if not part_end[0].isupper():
FIRST[part_begin] = FIRST.get(part_begin) + part_end[0]
def getFirst_2():
for str in sentences:
part_begin = ''
part_end = ''
part_begin += str.split('->')[0]
part_end += str.split('->')[1]
if part_end[0].isupper():
FIRST[part_begin] = FIRST.get(part_begin) + FIRST.get(part_end[0])
def getFisrt_3():
while(1):
test = FIRST
getFirst_2()
for i , j in FIRST.items():
temp = ""
for word in list(set(j)):
temp += word
FIRST[i] = temp
if test == FIRST:
break
def getFOLLOW_3():
while(1):
test = FOLLOW
getFollow()
for i , j in FOLLOW.items():
temp = ""
for word in list(set(j)):
temp += word
FOLLOW[i] = temp
if test == FOLLOW:
break
def getFollow():
for str in sentences:
part_begin = str.split("->")[0]
part_end = str.split("->")[1]
if len(part_end) == 1:
continue
else:
temp = []
for i in part_end:
temp.append(i)
temp.reverse()
if temp[0].isupper() :
FOLLOW[temp[0] ]= FOLLOW.get(temp[0]) + FOLLOW.get(part_begin)
temp1 = temp[0]
for i in temp[1:]:
if not i.isupper():
temp1 = i
else:
if temp1.isupper():
FOLLOW[i] = FOLLOW.get(i) + FIRST.get(temp1).replace("ε","")
if ('ε' in FIRST.get(temp1)):
FOLLOW[i] = FOLLOW.get(i) + FOLLOW.get(part_begin)
else:
FOLLOW[i] = FOLLOW.get(i) + temp1
temp1 = i
else:
temp1 = temp[0]
for i in temp[1:]:
if not i.isupper():
temp1 = i
else:
if temp1.isupper():
FOLLOW[i] = FOLLOW.get(i) + FIRST.get(temp1)
else:
FOLLOW[i] = FOLLOW.get(i) + temp1
temp1 = i
initail()
getFirst()
getFisrt_3()
getFisrt_3()
getFOLLOW_3()
getFOLLOW_3()
for i ,j in FIRST.items() :
str = j[0]
for temp in j[1:]:
str = str+ ',' +temp
print("FIRST("+ i + ")" + " = {"+str+"}")
for i ,j in FOLLOW.items():
str = j[0]
for temp in j[1:]:
str = str + ',' + temp
print("FOLLOW("+ i + ")" + " = {"+str+"}")