Python program Can someone help me please to write a Python program that support
ID: 3758437 • Letter: P
Question
Python program
Can someone help me please to write a Python program that support a processing of arithmetic expressions in postfix notation.
Expressions in postfix notation contain the operands on which the operation is performed followed by an operator. For example, 3 4 + is equal to 3 + 4 in the infix notation. float numbers and the following operators: + - * / ^ (all float operators) should be supported
There are a variety of ways to implement the postfix notation interpreter. One way is to use stacks. Another would be to use a tree.
The interpreter should accept strings of operators and operands seperated by spaces (no parenthesis) from standard input, and print the final result or output an error if the input is invalid. Each line will be a separate expression. EOF is the signal to quit.
Here is some sample input:
2.3 4 6.5 * + 3 5 + *
3 4 / 5 6 * - 2 -
3 2 - 2.8 +
Algorithm for evaluating postfix expressions
Start at the first token. For each token:
If it is an operand, push it on the stack.
Else if it is an operator, then
pop top value into y
if operator is binary:
pop top value into x
result <- x (oper) y
else
result <- (oper) y
push result onto stack
fi
fi
Continue until you've reached the end of the expression. There should be exactly one element in the stack; the result of the expression.
If you hit an operator and don't have sufficient operands on the stack (you'd better check) the expression is invalid. If you run out of tokens, and there's more than 1 operand on the stack, the input was invalid.
Simplle output
The result nedds to be printede (and just the result) of each expression, one per line, as each line is evaluated. No other output. So, interactively, this would be used in a very natural way.
If the expression is invalid you will print -E- .
Thaks!
Explanation / Answer
Python Postfix Evalution using Stack Data Structure Substite the Postfix expression j below code and get the result
from pythonds.basic.stack import Stack
def postfixEval(postfixExpr):
operandStack = Stack()
tokenList = postfixExpr.split()
for token in tokenList:
if token in "0123456789":
operandStack.push(int(token))
else:
operand2 = operandStack.pop()
operand1 = operandStack.pop()
result = doMath(token,operand1,operand2)
operandStack.push(result)
return operandStack.pop()
def doMath(op, op1, op2):
if op == "*":
return op1 * op2
elif op == "/":
return op1 / op2
elif op == "+":
return op1 + op2
else:
return op1 - op2
print(postfixEval('3 4 / 5 6 * - 2 -'))
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.