Professional Documents
Culture Documents
UNIVERSITY OF SARGODHA
Lab 8 Manual
Postfix Expression Evaluation
Date Performed
Marks obtained
Instructor Signature
CLO-1 Illustrate understanding of key concepts of Data structures
and Algorithms using Python PyCharm Platform
CLO-2 Design a programming application by applying concepts of
Data Structures and algorithms leading to the solution of a moderate
scale-programming problem.
CLO-3 Write lab notes, effective communication and the analysis of
the given problem to perform in the laboratory environment.
CLO-4 Demonstrate involvement in the Project as a team or
individually with respect to the contribution.
OBJECTIVE:
Objective of this experiment is to design, develop and implement a Python code for the evaluation of a
postfix expression.
The compiler first scans the expression to evaluate the expression b * c, then again scan the expression to
add a to it. The result is then added to d after another scan.
The repeated scanning makes it very in-efficient. It is better to convert the expression to postfix(or prefix)
form before evaluation.
The corresponding expression in postfix form is: abc*+d+. The postfix expressions can be evaluated easily
using a stack.
The Postfix notation is used to represent algebraic expressions. The expressions written in postfix form are evaluated
faster compared to infix notation as parenthesis are not required in postfix.
ALGORITHM:
1) Create a stack to store operands (or values).
2) Scan the given expression and do following for every scanned element.
a) If the element is a number, push it into the stack
b) If the element is a operator, pop operands for the operator from stack. Evaluate the operator
and push the result back to the stack
3) When the expression is ended, the number in the stack is the final answer
Python Program Code:
def scan_num(ch):
value = ord(ch)
return float(value - ord('0'))
def is_operator(ch):
if ch in ['+', '-', '*', '/', '^']:
return 1
return -1
def is_operand(ch):
if '0' <= ch <= '9':
return 1
return -1
def postfix_eval(postfix):
stk = []
for char in postfix:
if is_operator(char) != -1:
a = stk.pop()
b = stk.pop()
stk.append(operation(a, b, char))
elif is_operand(char) > 0:
stk.append(scan_num(char))
return stk[0]
if __name__ == "__main__":
post = "(10-3*34+8/4)*"
print(postfix_eval(post))
OUTPUT:
3.0
Outcomes Assessed:
CLO-1 Illustrate understanding of key concepts of Data structures and Algorithms using
Python PyCharm Platform.
CLO-2 Design a programming application by applying concepts of Data Structures and
algorithms leading to the solution of a moderate scale-programming problem.
CLO-3 Write lab notes, effective communication and analysis of the given problem to perform
in the laboratory environment.
CLO-4 Demonstrate involvement in the Project as a team or individually with respect to the
contribution.
Total