Although people may be very accustomed to reading and understanding calculations like those in the preceding assignments, it is evident they are not very self-evident or obvious in the world of computing. One way to simplify the problem is just to redefine how expressions are represented, to allow for simpler interpretation.
One knows that a plus sign means to add, but typically when a plus sign is encountered in the middle of an expression, there is not yet enough information to know what values are to be added. One has to continue scanning the expression to find the second operand, and also decide if there are other operations of higher precedence that must take place first. How much simpler it would be if a parser could know to add just as soon as the plus sign appears.
This is the motivation for a representation called postfix notation, in which all operators follow their operands. Here are some illustrations.
Infix Representation |
Postfix Representation |
Operations |
(1 + 2) * 3 |
1 2 + 3 * |
Add 1 and 2, then multiply by 3 |
1 + (2 * 3) |
1 2 3 * + |
Multiply 2 and 3, then add to 1 |
(1+2) * (6-4) |
1 2 + 6 4 – * |
Add 1 and 2, subtract 4 from 6, multiply |
Hewlett Packard has produced a line of calculators that expected all inputs to be in postfix form, so every operation key could compute the moment it was pressed.
The goal of this assignment is to convert an infix expression into a postfix expression. This can be accomplished using the same algorithm as was used to evaluate the infix expression, simply yielding a new expression instead of a computed value. In the last example, instead of adding, it would produce an expression ending with a plus sign. The multiplication function would similarly produce an expression from its operands, followed by the multiplication operator.
Applying a Linked List
One of the purposes of this course is to find the data structures that would assist in producing the best results as efficiently as possible. The linked list is quite serviceable for the needs of this assignment.
A linked list will be useful in the calculation portion of this assignment. As the postfix expression is scanned, values must be saved until an operator is discovered. Each operator would apply to the two values that precede it, and then its result would also be saved. As an extreme example, consider this expression:
1 2 3 4 5 * - + - multiply 4 * 5, subtract from 3, add to 2, subtract from 1
Note this is not at all the same meaning as:
1 2 * 3 - 4 + 5 - or 4 5 * 3 - 2 + 1 -
(If you need to more clearly see the difference, try inserting parentheses around all operations, such that each parentheses consists of two expressions followed by an operator.)
Defining a Linked List
The linked list is a rather simple data structure, and the required operations should be rather simple, so very little will be said here about what to do. Instead, here is a quick highlight of what should appear in your implementation. For consistency, call the implementation file linkedlist.py
Required Features in Implementation |
Nested Node class definition |
for single-linked list node |
with __slots__ |
to save list memory |
and __init__ |
a constructor |
__init__() |
a constructor for an empty list |
push(value) |
add a value in constant time |
pop() |
retrieve last insertion in constant time |
Good functions for Completeness / Practice |
top() |
return last insertion, without removal |
is_empty() |
Identify whether list is empty |
__len__() |
returns number of elements in list |
__iter__() |
iterator function (with yield statements) |
__str__() |
represents entire list as a string
For full credit, this must beno worse than log-linear time, not quadratic
|
The __iter__
function will be used to traverse a list to support __str__
.
__str__
would allow a list to be an argument to print()
for debugging
Assignment Specifications
Three new files are to appear in the solution to this assignment:
- linkedlist.py
- Implements a linked list as a class
- infixtoiter.py
- given an iterator to an infix expression,
produces a generator for a postfix expression
- evalpostfix.py
- evaluates a postfix expression, given an iterator
Do include newsplit.py
in your submission since it is a necessary part of the project.
You are also encouraged to insert your own unit testing into each file, but that will not be itself graded.
Helpful Time-Saving Hint:
One feature of an interpreted language like Python is to create code at run-time to execute. You can support all the calculations by taking advantage of this feature:
left="2"
right="2"
op = '+'
eval( left+op+right ) # evaluate "2+2" to get 4
This time-saving will become even more useful when we will support all the relation operators (such as > and ==)
Testing and Evaluation
Here are a few lines of code from the instructor’s solution and test at this time of writing:
(in infixtoiter.py)
from peekable import Peekable, peek
from newsplit import new_split_iter
def to_postfix( expr ):
return postfix_sum(Peekable(new_split_iter(expr)))
(in the test program)
from infixtoiter import to_postfix
from evalpostfix import eval_postfix
def test(expr):
print (expr, '=', eval_postfix(to_postfix(expr)) )
So here is the sequence of function calls as they operate on the input:
- The process begins with a character string in
expr
- It is broken into tokens by
new_split_iter
, which yields an iterator
- The Peekable constructor adds peek functionality
- The parsing functions in
infixtoiter
produce a linked list postfix expression
- That expression is evaluated by
eval_postfix
- The original string and computed value are displayed