# 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 multilinestring) so that it will also support an exponentiation operator
2. exponent has greater precedence than multiplication anddivision (Hint: think about PEMDAS)
# This is my Operator Precedence assignment in python from nltk import CFG import nltk grammar = nltk.CFG.fromstring("""
-
- Site Admin
- Posts: 899603
- Joined: Mon Aug 02, 2021 8:13 am