Assignment 2 --- Using stacks and queues to evaluate arithmetic expressions
In this assignment you will complete the code in
Evaluate.py to
read and evaluate infix expressions.
For the purposes of this assignment, an arithmetic expression
can contain only tokens that are spaces, integers, left or right parentheses, or
operators +, -, *, /.
- Enter Expression Your code should offer the option of reading infix expressions from either a file
or from the terminal into a string.
- Parse into Infix Token Queue Although there are a number of Python library functions for splitting
strings into pieces, I want you to loop through each character in the string and decide where each token begins
and ends. For example, given the string "(23 + 287)", the first token starts and ends at index 0,
the second starts at index 1 and ends at index 2, the third
starts and ends at index 4 (the space at index 3 is skipped), the fourth
starts at index 6 and ends at index 8 (the space at index 5 is skipped) and the fifth starts and ends at index 9.
Careful, there are some tricky cases to consider. For example, in the expression -3*5
the '-' is actually a "unary" operator rather than a binary one. That is, it is
part of the number and not considered an operator type token by itself. Before
you tackle this case, make sure everything else is working and then see if you can
figure this one out (and others like it).
- Convert Infix Token Queue into Postfix Token Queue.
- Evaluate Postfix Token Queue and print out the result both as
a string and a number. You will have to write the code to combine
two tokens that represent numbers into a new number token.
For example,