Eval

Let’s consider the evaluation of expressions formed from the 4 arithmetic operadors on float vales. For example, the result of evaluating 0.0+5.0-1.0+2.0-3.0 is 3.0.

You are required to implement the following functions in the module eval_module (file eval_module.py):

The first function is

eval_op(v1, op, v2)

such that

given v1, v2 both float and op a str

returns two values:

  • a bool which is True if and only if op one of the following str: '+', '-' , '*' , '/' and, if it is '/' v2 must not be 0.0, and is False otherwise.

  • a float rounded to 1 decimal with either:

    • the result from applying the operator op to v1 i v2, if the previous value is True

    • or v1, if the previous value is False.

For example:


>>> eval_op(0.0, '+', 5.0)
(True, 5.0)
>>> eval_op(8.0, '/', 3.0)
(True, 2.7)
>>> eval_op(8.0, '/', 0.0)
(False, 8.0)
>>> eval_op(8.0, '//', 3.0)
(False, 8.0)

Doctests are available in the eval_op.test file.


Once eval_op is ready, the second function required is

eval(val0, op1, val1, op2, val2, op3, val3, op4, val4)

such that

given 9 parameters where all valX are float and all opX are str

returns two values:

  • a bool such that is True if all the operations succeeded and False otherwise.

  • a float such that it is either:

    • val0 if the previous value is False

    • the result from operating val0 with the 4 arithmetic operations and the value next to it in left to right order.

This function must call the previous function.

Per exemple:


>>> eval(0.0, '+', 5.0, '-', 1.0, '+', 2.0, '-', 3.0)
(True, 3.0)
>>> eval(0.0, '+', 5.0, '-', 1.0, '*', 2.0, '/', 3.0)
(True, 2.7)
>>> eval(0.0, '+', 0.0, '-', 0.0, '*', 0.0, '/', 0.0)
(False, 0.0)
>>> eval(0.0, '+', 5.0, '-', 1.0, '*', 2.0, '//', 3.0)
(False, 0.0)

Doctests are available in the eval.test file.