First write the following expression in postfix Reverse Poli
First write the following expression in postfix (Reverse Polish) notation. Remember the rules of precedence for arithmetic operators! (A-B+C*(D*E-F)/(G+H*K) I have done the 1st question. Second, Write a program to evaluate the above arithmetic statement using a stack organized computer with zero-address instructions (so only pop and push can access memory).
I would like everyone to identify the storage location for each of the variables in these problems. Also, please state in your provided documentation, what the specific values are for the inputs you are using.
Solution
from pythonds.basic.stack import Stack
def infixToPostfix(infixexpr):
prec = {}
prec[\"*\"] = 3
prec[\"/\"] = 3
prec[\"+\"] = 2
prec[\"-\"] = 2
prec[\"(\"] = 1
opStack = Stack()
postfixList = []
tokenList = infixexpr.split()
for token in tokenList:
if token in \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" or token in \"0123456789\":
postfixList.append(token)
elif token == \'(\':
opStack.push(token)
elif token == \')\':
topToken = opStack.pop()
while topToken != \'(\':
postfixList.append(topToken)
topToken = opStack.pop()
else:
while (not opStack.isEmpty()) and \\
(prec[opStack.peek()] >= prec[token]):
postfixList.append(opStack.pop())
opStack.push(token)
while not opStack.isEmpty():
postfixList.append(opStack.pop())
return \" \".join(postfixList)
print(infixToPostfix(\"A * B + C * D\"))
print(infixToPostfix(\"( A + B ) * C - ( D - E ) * ( F + G )\"))
