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....
python problem: ( use a loop to read each character from the string and insert into...
python problem: ( use a loop to read each character from the string and insert into the stack) 1. The function main a5.py continually asks the user for a string, and calls isPalindrome to check whether each string is a palindrome. A palindrome is a word or sequence that reads the same backward as forward, e.g., noon, madam or nurses run. 2. Your function must ignore spaces: when the user enters 'nurses run', the function returns True, to indicate that...
Stack Queue Program Implement a Stack class using the List Class you developed earlier. Test your...
Stack Queue Program Implement a Stack class using the List Class you developed earlier. Test your Stack class by determining if the following strings have matching open and closing ( ) and/or [ ] and/or { }. To test matches, push open (, [, { onto the stack. Input a close char, pop off the stack and see if input matches symbol form stack.   Use the following data to test your code:                               ( )                               [ ] ( )...
Description: In this assignment, you need to implement a recursive descent parser in C++ for the...
Description: In this assignment, you need to implement a recursive descent parser in C++ for the following CFG: 1. exps --> exp | exp NEWLINE exps 2. exp --> term {addop term} 3. addop --> + | - 4. term --> factor {mulop factor} 5. mulop --> * | / 6. factor --> ( exp ) | INT The 1st production defines exps as an individual expression, or a sequence expressions separated by NEWLINE token. The 2nd production describes an...
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...
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 -...
Please create a python module named homework.py and implement the functions outlined below. Below you will...
Please create a python module named homework.py and implement the functions outlined below. Below you will find an explanation for each function you need to implement. When you are done please upload the file homework.py to Grader Than. Please get started as soon as possible on this assignment. This assignment has many problems, it may take you longer than normal to complete this assignment. This assignment is supposed to test you on your understanding of reading and writing to a...
I NEED TASK 3 ONLY TASK 1 country.py class Country:     def __init__(self, name, pop, area, continent):...
I NEED TASK 3 ONLY TASK 1 country.py class Country:     def __init__(self, name, pop, area, continent):         self.name = name         self.pop = pop         self.area = area         self.continent = continent     def getName(self):         return self.name     def getPopulation(self):         return self.pop     def getArea(self):         return self.area     def getContinent(self):         return self.continent     def setPopulation(self, pop):         self.pop = pop     def setArea(self, area):         self.area = area     def setContinent(self, continent):         self.continent = continent     def __repr__(self):         return (f'{self.name} (pop:{self.pop}, size: {self.area}) in {self.continent} ') TASK 2 Python Program: File: catalogue.py from Country...