This post has been de-listed
It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.
So I need help in trying to compute the First/Follow functions in Python for Context Free Grammars. What I understand is that for each terminal, the FIRST for that terminal will just be the terminal itself.
But for non-terminals, it should iterate through each production rule until it finds either epsilon(null) or a terminal. I wrote code based on this understanding but I'm stuck in trying to iterate through production rules and properly update the nonterminals to their FIRST[] value. Any help would be appreciated.
This is what I've done so far. In the pseudocode I'm following, the last loop in the computeFirst function should keep executing until no changes happen anymore. I thought to implemement that I would create another variable which saves the state of FIRST[x] and keeps checking back with it to see if there was a change
#'e' is epsilon
NONTERMS = ['S','E','E^','A','T','T^','M','F']
TERMS = [' ','-','*','(',')','n']
FIRST ={}
grammar = {'E':[['T','E^']],
'E^':[['A','T','E^'],['e']],
'A':[[' '],['-']],
'T':[['F','T^']],
'T^':[['M','F','T^'],['e']],
'M':[['*']],
'F':[['(','E',')'],['n']]}
def computeFirst(g):
for a in TERMS:
FIRST[a]=[a]
for i in NONTERMS:
FIRST[i]=[]
for x in g:
for i in g[x]:
FIRST[i]=computeFirstOfList[i]
def computeFirstOfList(p):
tmp=[]
k=0
n=len(p)
computeFirst(grammar)
Subreddit
Post Details
- Posted
- 6 years ago
- Reddit URL
- View post on reddit.com
- External URL
- reddit.com/r/learnpython...