Programming project 3

Download the archive pp3.zip. It contains all the files for this project.

In this project you will improve the calculator we discussed in class. Before you start, make sure you understand the implementation of the power operator ^. You should understand how we achieved that the power operator is right-associative, while all other operators are left-associative.

All changes will be made in the file calculator.py. You are not allowed to change tokens.py. (In any case, you will only upload calculator.py to the submission server.)

The unit tests in test.py allows you to do some basic tests of your implementation:

$ python3 test.py 
EEEE
======================================================================
ERROR: test_absolute (__main__.TestCalculator)
======================================================================
ERROR: test_division (__main__.TestCalculator)
======================================================================
ERROR: test_e (__main__.TestCalculator)
======================================================================
ERROR: test_pi (__main__.TestCalculator)
----------------------------------------------------------------------
Ran 4 tests in 0.001s

FAILED (errors=4)
All tests will pass when you are done with the three tasks.

Mathematical constants

Implement the constants pi and e (in Python, use math.pi and math.e).

Enter an expression: pi
==> 3.14159
Enter an expression: 2 * pi
==> 6.28319
Enter an expression: e
==> 2.71828
Enter an expression: e^2
==> 7.38906
Enter an expression: 1 - e^-1
==> 0.632121

Division by zero

When a division by zero is attempted, the calculator should stop evaluating the expression, and instead indicate a "Division by zero" error. The error indicator must point at the division operator.

Enter an expression: 4.5 / 0
Error: Division by zero
4.5 / 0
    ^
Enter an expression: 1 + 2 + 3 + 4 / (10 - 2 * 5)
Error: Division by zero
1 + 2 + 3 + 4 / (10 - 2 * 5)
              ^

Absolute value

We now add an operator to compute the absolute value of an expression. The operator consists of two vertical bars. In between, an arbitrary expression can be written:

Enter an expression: |17|
==> 17
Enter an expression: |-17|
==> 17
Enter an expression: 3 + |34 - 76|
==> 45
Enter an expression: -2 + |-2|
==> 0
Enter an expression: |1374 - 2746|
==> 1372
Enter an expression: 9 - |1 - |9 - 3 * 4||
==> 7
In Python, use the abs function to compute the absolute value.

Hint: How do you need to update the syntax diagram?

Submission: Upload your file calculator.py to the submission server.