Python
The final value of the evaluation of the postfix expression 6 2 + 5 * 8 4 / - is ----------
Algorithm for Postfix Evaluation
Progarm code in Python
Program Sample Output Screenshot
Program Code to copy
# Class to evaluate the expression
class PostfixEvaluation:
# Constructor to initialize the class variables
def __init__(self):
self.top = -1
# declare a stack
self.array = []
# check if the stack is empty
def isEmpty(self):
return True if self.top == -1 else False
# Return item on stack top
def peek(self):
return self.array[-1]
# Pop item from the stack
def pop(self):
if not self.isEmpty():
self.top -= 1
return self.array.pop()
else:
return "$"
# Push item into the stack
def push(self, op):
self.top += 1
self.array.append(op)
# This function will evaluate the postfix expression
def evaluatePostfixExpression(self, expression):
# Iterate over items in the expression array
for item in expression:
# push in the stack if it is an operand
if item.isdigit():
self.push(int(item))
# if this is an operator then pop operands from stack and
# evaluate and push evaluated value back in stack
else:
val1 = str(self.pop())
val2 = str(self.pop())
self.push(int(eval(val2 + item + val1)))
return self.pop()
# Driver program to test above function
expression = "6 2 + 5 * 8 4 / -"
evaluater = PostfixEvaluation()
value = evaluater.evaluatePostfixExpression(expression.split())
print("The final value of the evaluation of the postfix expression %s is %d" %
(expression, value))
Get Answers For Free
Most questions answered within 1 hours.