3 Write a program for generating derivation sequence/language for the given sequence of productions
def generate_derivation_sequence(start_symbol, productions, max_depth=10):
derivation_sequence = []
generate_derivation(start_symbol, productions, derivation_sequence, max_depth)
return derivation_sequence
def generate_derivation(symbol, productions, derivation_sequence, max_depth, depth=0):
if depth > max_depth:
return
if symbol.islower() or symbol.isupper():
# Non-terminal symbol, apply a production rule
for production in productions:
if production.startswith(symbol + ' ->'):
new_symbols = production.split(' -> ')[1].split()
for new_symbol in new_symbols:
generate_derivation(new_symbol, productions, derivation_sequence, max_depth, depth + 1)
else:
derivation_sequence.append(symbol)
else:
# Terminal symbol, add it to the derivation sequence
derivation_sequence.append(symbol)
# Example usage:
productions = [
'S -> a A',
'A -> b B',
'B -> c | ε'
]
start_symbol = 'S'
derivation_sequence = generate_derivation_sequence(start_symbol, productions)
print('Derivation Sequence:', ' '.join(derivation_sequence))
No comments