Question

(For Python) Evaluating Postfix Arithmetic Expressions. In this project you are to implement a Postfix Expression...

(For Python)

Evaluating Postfix Arithmetic Expressions. In this project you are to implement a Postfix Expression Evaluator as described in section 7-3b of the book. The program should ask the user for a string that contains a Postfix Expression. It should then use the string's split function to create a list with each token in the expression stored as items in the list. Now, using either the stack classes from 7.2 or using the simulated stack functionality available in a Python list, evaluate the expression. The pseudo-code shown in the book is:

            Create a new stack

            While there are more tokens in the expression

                        Get the next token

                        If the token is an operand (that is an integer number)

                                    Push the token onto the stack

                        Else If the token is an operator (+, -, * or /)

                                    Pop the top two operands from the stack

                                    Apply the operator to the two operands

                                    Push the resulting value onto the stack

                        Else

                                    Say that the input was not a valid expression

            Pop the value at the top of the stack and display as the result

An example expression might be:

            3 4 5 + * = 27 (push 3, push 4, push 5, pop 5, pop 4, add = 9, push 9, pop 9, pop 3,

                        multiply = 27, push 27, pop 27 as the answer

Some things to think about:

            What happens if there are two many operators or operands? How do we catch that?

Here's a start-up that uses the ArrayStack classes from 7.2. Or, if you want, you can replace the ArrayStack with just a Python List. Your choice:

from arraystack import ArrayStack

def main():

    sParse = input("Enter A PostFix String...")

    sToken = sParse.split()

    oStack = ArrayStack()

    nCounter = 0

"""How can we check to see if the stuff in our list is correct input? (That is integers and operators)

   Follow the pseudo code from here to go through the sToken list

   and push and pop tokens to get the result. Once you get it working with

   good input, think about what to check to give an error when bad input

   (maybe too many operators, or too many numbers)"""

def compute(a,b,op):

"""when I wrote this, I stuck my actual calculations in a separate function

   that checked the op and then did the op against a and b. You could

   have this inline with the above if you wish. Just made cleaner code.   """

main()

Please indent properly.

Homework Answers

Answer #1

sol: In the above question, we have to take a string of post fix expression from the user and compute the result. We have to store the expression in a list using split() function. We shall use the stack functionality of lists available. using the given algorithm we have to go through the expression and keep evaluating. We have to check 3 cases of wrong input 1) if the expression has non numeric or non operator values 2) many operators that is if the operators are more than the operands it can work on 3)more numbers that is no more operator left to work on the remaining number.

CODE:

def convert(string):
stack=list(string.split(" "))#splitting to list

return stack
def evaluate(stack):
f=0
postfix=[]
for s in stack:
if(s.isnumeric()== True):#checking if data is numeric
postfix.append(s);
elif (s=='*' or s=='+' or s=='/' or s=='-'):#checking if data is operator
  
if(len(postfix)==0 or len(postfix)==1):#checking for more operators by checking sufficient values to pop
f=1
print("Wrong Expression")
break
else:

num1=int(postfix.pop())
num2=int(postfix.pop())
postfix.append(compute(num1,num2,s))
  
else:#for non operator or non numeric data
f=1
print("Wrong Expression")
break

if (len(postfix)!=1 and f==0):#checking for more numbers by checking length of list
f=1
print("Wrong Expression")
if(f==0): #if f is 0 that is no fault found
print("Result: ",(postfix.pop()))#popping result
def compute(a,b,op):
  
if(op== '+'):
return int(a+b)
elif (op== '-'):
return int(b-a)
elif (op== '/'):
return int(b/a)
else:
return int(a*b)
  
expr=input("Enter a postfix expression: ")#calling functions
stack=convert(expr)
evaluate(stack)

CODE SNAPSHOT FOR UNDERSTANDING THE INDENTATION:

EXECUTION:

The first 2 are correct expressions.

3rd expression has extra operators.

4th expression has extra numbers.

5th expression has non-integer data.

All the cases have been tested.

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
in Java In this exercise, you'll write a Java version of the infix-to-postfix conversion algorithm. These...
in Java In this exercise, you'll write a Java version of the infix-to-postfix conversion algorithm. These same mechanisms can be used as a part of writing a simple compiler. Write class InfixToPostfixConverter co convert an ordinary infix arithmetic expression (assume a valid expression is entered) with single-digit integers (to make things easier) such as (6 + 2) • 5 - 8 / 4 to a postfix expression. The postfix version (no parentheses are needed) of this infix expression is 6...
[PART ONE OF PROJECT, ALREADY COMPLETED] An accumulator is a primitive kind of calculator that can...
[PART ONE OF PROJECT, ALREADY COMPLETED] An accumulator is a primitive kind of calculator that can evaluate arithmetic expressions. In fact, the Arithmetic-Logic Unit (ALU) of the rst computers was just an accumulator. An arithmetic expression, as you know, consists of two kinds of tokens: operands and operators All our operands will be (float) numbers and for a start, we shall use only two operators: + (plus) and - (minus) A sample run of the program would look like this....
Let s be a string that contains a simple mathematical expression, e.g., s = '1.5 +...
Let s be a string that contains a simple mathematical expression, e.g., s = '1.5 + 2.1-3' s = '10.0-1.6 + 3 - 1.4' The expression will have multiple operands. We don't know exactly how many operands there are in s. The operator will be one of the following: +, -. Write a function called plus_minus() that takes s as the input, interpret the expression, then evaluate and return the output. Note: The use of the eval() is not allowed...
Code in JAVA The requirements are as follows: The input will be in a text file...
Code in JAVA The requirements are as follows: The input will be in a text file whose name is given by arg[0] of main(). It will contain a fully-parenthesized infix expression containing only: "(", ")", "+", "-" and integers. Need help on the main and fixing the Queue. //Input: ( ( 1 + 2 ) - ( ( 3 - 4 ) + ( 7 - 2 ) ) ) ( ( 1 + 2 ) - ( 3 -...
I've posted this question like 3 times now and I can't seem to find someone that...
I've posted this question like 3 times now and I can't seem to find someone that is able to answer it. Please can someone help me code this? Thank you!! Programming Project #4 – Programmer Jones and the Temple of Gloom Part 1 The stack data structure plays a pivotal role in the design of computer games. Any algorithm that requires the user to retrace their steps is a perfect candidate for using a stack. In this simple game you...