Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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:

    1. Create a stack to store operands (i.e. numbers)
    2. Walk through the expression string element by element:
      1. If the element is a number, push it into the stack
      2. 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
    3. 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

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Database And Transaction Processing

Authors: Philip M. Lewis, Arthur Bernstein, Michael Kifer

1st Edition

0201708728, 978-0201708721

More Books

Students also viewed these Databases questions