Python Issue Postfix notation (also known as Reverse Polish Notation or RPN in s
ID: 3748269 • Letter: P
Question
Python Issue
Postfix notation (also known as Reverse Polish Notation or RPN in short) is a mathematical notation in which operators follow all of its operands. It is different from infix notation in which operators are placed between its operands.
The algorithm to evaluate any postfix expression is based on stack and is pretty simple:
Initialize empty stack
For every token in the postfix expression (scanned from left to right):
If the token is an operand (number), push it on the stack
Otherwise, if the token is an operator (or function):
Check if the stack contains the sufficient number of values (usually two) for given operator
If there are not enough values, finish the algorithm with an error
Pop the appropriate number of values from the stack
Evaluate the operator using the popped values and push the single result on the stack
Return the final result of the calculation
Implement a function def eval_postfix(expression_str) that evaluates and returns the result of a postfix expression. The postfix expression to be evaluated is passed to the function as a string parameter. Each component of the postfix expression string is separated by a single space. Your function needs to support the following operations: "+", "-", "*", "/", "%" and "**". Your function should also work with values consisting of more than one digit.
For example:
Test Result print(eval_postfix("2 3 * 4 +")) 10
print(eval_postfix("2 3 4 + *")) 14
Explanation / Answer
def evaluate_postfix(input_string):
stack = list() # initializing the empty stack
for i in input_string:
result = 0; #result variable for storing the result
if i in "0123456789": #checking whether input symbol is number or not
stack.append(int(i))
elif stack: #checking whether stack is not empty
operand1=stack.pop() # removing the top value of the stack
operand2=stack.pop() #removing the next top value of the stack
if i == "+":
result = operand1+operand2
elif i == "-":
result = operand2 - operand1
elif i == "*":
result = operand1 * operand2
elif i == "/":
result = operand2 / operand1
elif i == "^": #taking raise power as ^ operator
result = operand2 ** operand1
elif i == "%":
result= operand2 % operand1
if result!=0: ##checking result is zero or not
stack.append(result) ## if any result we are ushing it into stcak
return stack.pop() ## returning the final stack value
input_string=raw_input("enter the postfix string "); #taking the expression string as input
final_val=evaluate_postfix(input_string) #calling the function
print final_val #printing the final result
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.