Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Modify the factor() method to implement the new rule ( ) in the below python program. ========================================================================================= ''' This program implements a recursive descent parser

Modify the factor() method to implement the new rule () in the below python program.

=========================================================================================

''' This program implements a recursive descent parser for the CFG below:

The grammar has added pi and unary minus to the previous program. Also, the parse function is now called in a loop, so you can evaluate one expression after another. ------------------------------------------------------------ 1 {+ | -} 2 {* | /} 3 | - | () ''' import math

class ParseError(Exception): pass

#============================================================== # FRONT END PARSER #==============================================================

op_code = {'+':'ADD', '-':'SUB', '*':'MUL', '/':'DIV'} reg_stack = []

def get_reg(): r = 1 while r in reg_stack: r += 1 reg_stack.append(r) return r

i = 0 # keeps track of what character we are currently reading. err = None #--------------------------------------- # Parse an Expression {+ | -} # def exp(): global i, err

value = term() while True: if w[i] == '+': i += 1 value = binary_op('+', value, term()) elif w[i] == '-': i += 1 value = binary_op('-', value, term()) else: break

return value #--------------------------------------- # Parse a Term {+ | -} # def term(): global i, err

value = factor() while True: if w[i] == '*': i += 1 value = binary_op('*', value, factor()) elif w[i] == '/': i += 1 value = binary_op('/', value, factor()) else: break

return value #--------------------------------------- # Parse a Factor - | | () # def factor(): global i, err value = None

if w[i] == '-': i += 1 return unary_op('-', factor()) # add an elif here to handle w[i] == '(' # remember to check for matching ')' else: try: value = atomic(w[i]) i += 1 # read the next character except ValueError: print('value expected') value = None

if value == None: raise ParseError return value

#============================================================== # BACK END PARSER (ACTION RULES) #==============================================================

def binary_op(op, lhs, rhs): if op == '+': return lhs + rhs if op == '-': return lhs - rhs if op == '*': return lhs * rhs if op == '/': return lhs / rhs return None

def unary_op(op, rhs): if op == '-': return -rhs else:return None

def atomic(x): return float(x)

#============================================================== # User Interface Loop #============================================================== w = input(' Enter expression: ') while w != '': #------------------------------ # Split string into token list. # for c in '()+-*/': w = w.replace(c, ' '+c+' ') w = w.split() w.append('$') # EOF marker

print(' Token Stream: ', end = '') for t in w: print(t, end = ' ') print(' ') i = 0 reg_stack = [] try: print('Value: ') print(exp()) # call the parser except: print('parse error') print() if w[i] != '$': print('Syntax error:') print('read | un-read: ', end = '') for c in w[:i]: print(c, end = '') print(' | ', end = '') for c in w[i:]: print(c, end = '') print() w = input(' Enter expression: ') #print(w[:i], '|', w[i:]) =====================================================================

The output should read like below :

=====================================================================

Enter expression: -((2*(3 + 4) - 5) + 6)/2 Token Stream: - ( ( 2 * ( 3 + 4 ) - 5 ) + 6 ) / 2 $ Value: -7.5 read | un-read: -((2*(3+4)-5)+6)/2 | $

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Business Process Driven Database Design With Oracle PL SQL

Authors: Rajeev Kaula

1st Edition

1795532386, 978-1795532389

More Books

Students also viewed these Databases questions

Question

9. Explain the relationship between identity and communication.

Answered: 1 week ago

Question

a. How do you think these stereotypes developed?

Answered: 1 week ago

Question

a. How many different groups were represented?

Answered: 1 week ago