Page 1 of 1

# This is my Operator Precedence assignment in python from nltk import CFG import nltk grammar = nltk.CFG.fromstring("""

Posted: Mon Jul 11, 2022 9:53 am
by answerhappygod
# This is my Operator Precedence assignment in python
from nltk import CFGimport nltk
grammar = nltk.CFG.fromstring("""S -> ExpressionExpression -> Expression PlusMinus Term | TermTerm -> Factor | Term TimesDivide FactorFactor -> 'X' | 'Y' | 'Z' PlusMinus -> '+' | '-'TimesDivide -> '*' | '/' """)
print('The productions are:', grammar.productions())
from nltk import ChartParserparser = ChartParser(grammar)sentence = 'X + Y * Z'.split()print('The statement is', sentence)for tree in parser.parse(sentence): print(tree) tree.draw()
1. change the context free grammar (in the multiline string) sothat it will also support an exponentiation operator
2. exponent has greater precedence than multiplication anddivision (Hint: think about PEMDAS)