First&follow
First&follow
def first_of(symbol):
# If FIRST(symbol) is already computed, return it
if symbol in first and first[symbol]:
return first[symbol]
# If symbol is a terminal (e.g., 'a'), its FIRST is itself
if not symbol.isupper():
return {symbol}
# For non-terminals (e.g., 'A'), compute recursively
result = set()
for production in grammar[symbol]: # Loop through all productions of the
symbol
for char in production: # Check each character in the production
char_first = first_of(char) # Recursive call to compute FIRST of
the character
result.update(char_first - {'ε'}) # Add all except epsilon
if 'ε' not in char_first: # Stop if epsilon is not present
break
else: # If all characters can produce epsilon, add epsilon
result.add('ε')
first[symbol] = result
return result
# Example Grammar
grammar = {
'E': ['T+E', 'T'],
'T': ['F*T', 'F'],
'F': ['(E)', 'id']
}
# Print results
print("FIRST Sets:")
for nt in grammar:
print(f"FIRST({nt}) = {first_sets[nt]}")
print("\nFOLLOW Sets:")
for nt in grammar:
print(f"FOLLOW({nt}) = {follow_sets[nt]}")