Question: Write a function that evaluates an arithmetic expression with the following requirements: - Input is the tuple of parsed tokens provided as the output of
Write a function that evaluates an arithmetic expression with the following requirements:
Input is the tuple of parsed tokens provided as the output of parseexpression function, ie a list of characters for operators and float values.
Output is the result of the evaluation of the expression ie a floating point number
Function should raise erception when an invalid expression is given
Use double stack implementation based expression evaluation algorithm that was provided in the lecture slides.
Use FloatArrayStack with capacity of for numbers operands
Use ListStack for operators
You will improve the algorithm given in the textbook so that it supports parentheses as well
Allowed operators are defined in function parseexpression, their precedences shall be computed using pred function provided below, ie precedences are:
for T and gamma
for and
for and
Here is how you improve the algorithm when parentheses are provided in the input:
If the operator is C push it to the operator stack
If the operator is I perform doOp opreation until T is popped from the stack
Note that gamma has lower precedence than alf other arithmetic operators and gamma is never pushed to the stack
You may define multiple functions or global variables
There is a builiin python function called evalo. which evaluates an expression it is forbidden to use that function in your solution, however you can use it to test your code.
You will get partial points anyway even if you don't implement parentheses, it is recommended that you first implement the algorithm given in the slides, then improve it by adding parenthesis support.
OPERATORS
def precop:
return OPERATORS.indexop
def evaltokenstokens:
floats FloatArrayStack
ops ListStack
# YOUR CODE HERE
raise NotImplementedError
def evalexpressionexpression:
tokens parseexpressionexpression
return evaltokenstokens
#You can use the following code to test you code
assert evaltokens
assert evaltokens
assert evaltokens
assert evaltokens
#You can also use the given parseexpression function
assert evalexpressionmathrmEmathrmemathrmE
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
