Question: Use Python to evaluate prefix expressions. Your algorithm will be recursive. We must be able to recognize tokens in the expression. Notice that we can't
Use Python to evaluate prefix expressions. Your algorithm will be recursive.
We must be able to recognize tokens in the expression. Notice that we can't simply split the expression on spaces since "(" and "+" are separate symbols, but are not separated by spaces.
You must create the prefixReader function which does the following:
-Reads each text line in the input file (which was passed as a command argument). For each text line:
-It should print the prefix text string, preceded by "> "
-It must tokenize the expression using Python's regex (use the re module).
-Reset the global current parsing pos to 0
-It should invoke prefixEval passing the token array. If that function returned successfully (i.e., it didn't raise an exception), it should print the value returned from prefixEval.
-It should provide a try except block which prints errors. After printing an error do not exit the program.
You must create the prefixEval function which is passed a token array and modifies the global current parsing pos:
-Based on the token at the current position, if if is a:
( It is evaluating a function. prefixEval should treat the next token as a function name. It now needs to evaluate the arguments for that function:
-Assume the function has only two arguments. See extra credit for handling a variable number of arguments.
-It should invoke prefixEval to get the value of each argument (appropriately advancing the global current parsing position).
-It should advance the global current parsing position past its corresponding ")".
-It should invoke evalOperator passing the function and arguments and return that value as prefixEval's functional value.
number It should return that number's integer value as prefixEval's functional value.
-prefixEval should use another function to actually apply the function to the operands. The following functions must be supported:
+ addition
- minus - subtracts the second operand from the first
* multiplication
/ division - divides the second operand into the first, truncating the result
> greater than (numeric)
< less than (numeric)
and Boolean and returns True or False
or Boolean or returns True or False
-Before returning, prefixEval advances the global current parsing position to the position immediately after its expression
Sample Output:
> (* 2 15)
30
> (- (* 12 2)(* 2 3 ))
18
> (* 5 (/ 5 2))
10
> (or (> 6 13) (< 15 2))
False
> (and (> 13 6) (> 17 3))
True
> (+ 1 (* 12 4 )(* 2 2)
Missing closing ')'
> (/ (+ 3 5))
Incorrect number of operands - must be 2 for '/'
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
