(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.
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.
Get Answers For Free
Most questions answered within 1 hours.