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 parse_expression function, ie. a list of characters (for operators) and float values.
* Output is the result of the evaluation of the expression i.e. 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 20) 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 parse_expression, their precedences shall be computed using pred function provided below, ie. precedences are:
-1 for 'T and \(\gamma \)
-2 for '+' and '-'
-3 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 doOp0 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 buili-in 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 prec(op):
return 1+ OPERATORS.index(op)//2
def eval_tokens(tokens):
floats = FloatArrayStack(20)
ops = ListStack()
# ============ YOUR CODE HERE ============
raise NotImplementedError()
```
```
def eval_expression(expression):
tokens = parse_expression(expression)
return eval_tokens(tokens)
```
\#You can use the following code to test you code
assert \(3.0==\) eval_tokens((3.0,))
assert \(8.0==\) eval_tokens((3.0,'+',5.0))
assert \(13.0==\) eval_tokens((3.0,'+',5.0,'*',2.0))
assert \(16.0=\) eval_tokens(('(',3.0,'+',5.0,')','*',2.0))
\#You can also use the given parse_expression function
assert \(0.1342281879194631=\) eval_expression("\(6^{*}(2.0+3)/.(23.5+(.2\mathrm{E}3+0.1\mathrm{e}+3-10000\mathrm{E}-2))\)")
Write a function that evaluates an arithmetic

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!