Question
I need help for Python please :) # Constants OPERATORS = +-*/ def postfix(string): ------------------------------------------------------- Evaluates a postfix expression. Use: answer = postfix(string) -------------------------------------------------------
I need help for Python please :)
# Constants
OPERATORS = "+-*/"
def postfix(string):
"""
-------------------------------------------------------
Evaluates a postfix expression.
Use: answer = postfix(string)
-------------------------------------------------------
Parameters:
string - the postfix string to evaluate (str)
Returns:
answer - the result of evaluating string (float)
-------------------------------------------------------
"""
Add this function to the PyDev module functions.py. Test it from t05.py.
The function must use a single stack to do its work.
The postfix and infix expression and how to evaluate an infix expression is discussed in Lesson 4: Applications of Stack
In a postfix expression, operators follow operands. Thus the infix expression:
12 - 5
is written as postfix expression:
12 5 -
which evaluates to 7.
In postfix expressions as the operations are performed in the order that they appear. The expression:
4 5 + 12 * 2 3 * -
is equivalent to (4 + 5) * 12 - 2 * 3 and evaluates to 102.
The algorithm for evaluation postfix expressions is:
-
- Create a stack to store operands (i.e. numbers)
- Walk through the expression string element by element:
- If the element is a number, push it into the stack
- If the element is an operator, pop two operands from stack. Evaluate the operator with the top element on the right of the operator and the next element on the left of the operator, and push the result back to the stack
- When the expression is finished, the number on the top of the stack is the final answer. The stack should be empty after this number is popped.
You do not have to do any error handling on poorly written postfix expressions. A valid postfix expression has at least one number in it.
Thanks!
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started